`
--reload language
if(uiTranslationFile) then
	Infinity_DoFile("L_" .. uiTranslationFile)
else
	Infinity_DoFile("L_en_us")
end
listMetaInfo = {}
combatLog = {}


currentPanelID = 0

function displayTHAC()
	thactxt = ''
	thactxt =  characters[currentID].THAC0.current

	if (characters[currentID].THAC0.offhand ) then
		thactxt = thactxt .. '\n' .. characters[currentID].THAC0.offhand
	end

	return thactxt
end

function displayCompiledAC()
	local compiledAC = characters[currentID].AC.current

	if characters[currentID].AC.crushing ~= 0 or characters[currentID].AC.missile ~= 0 or characters[currentID].AC.piercing ~= 0 or characters[currentID].AC.slashing ~= 0 then
		compiledAC = compiledAC .. " (" .. t("MODIFIERS_LABEL") .. ": "

		local numMods = 0
		if characters[currentID].AC.crushing > 0 then
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>","+"..characters[currentID].AC.crushing)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_CRUSHING")
			removeStringTokenLua("<ACTOKEN>")
		elseif characters[currentID].AC.crushing < 0 then
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>",characters[currentID].AC.crushing)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_CRUSHING")
			removeStringTokenLua("<ACTOKEN>")
		end

		if characters[currentID].AC.missile > 0 then
			if numMods > 0 then
				compiledAC = compiledAC .. ", "
			end
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>","+"..characters[currentID].AC.missile)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_MISSILE")
			removeStringTokenLua("<ACTOKEN>")
		elseif characters[currentID].AC.missile < 0 then
			if numMods > 0 then
				compiledAC = compiledAC .. ", "
			end
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>",characters[currentID].AC.missile)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_MISSILE")
			removeStringTokenLua("<ACTOKEN>")
		end

		if characters[currentID].AC.piercing > 0 then
			if numMods > 0 then
				compiledAC = compiledAC .. ", "
			end
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>","+"..characters[currentID].AC.piercing)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_PIERCING")
			removeStringTokenLua("<ACTOKEN>")
		elseif characters[currentID].AC.piercing < 0 then
			if numMods > 0 then
				compiledAC = compiledAC .. ", "
			end
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>",characters[currentID].AC.piercing)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_PIERCING")
			removeStringTokenLua("<ACTOKEN>")
		end

		if characters[currentID].AC.slashing > 0 then
			if numMods > 0 then
				compiledAC = compiledAC .. ", "
			end
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>","+"..characters[currentID].AC.slashing)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_SLASHING")
			removeStringTokenLua("<ACTOKEN>")
		elseif characters[currentID].AC.slashing < 0 then
			if numMods > 0 then
				compiledAC = compiledAC .. ", "
			end
			numMods = numMods + 1
			setStringTokenLua("<ACTOKEN>",characters[currentID].AC.slashing)
			compiledAC = compiledAC .. " " .. t("ACMOD_VS_SLASHING")
			removeStringTokenLua("<ACTOKEN>")
		end

		compiledAC = compiledAC .. ")"
	end

	return compiledAC
end

function displaySTR()
	strtxt = characters[currentID].attr.str.current

	if characters[currentID].attr.str.current == 18 and characters[currentID].attr.str.extra > 0 then
		if characters[currentID].attr.str.extra == 100 then
			strtxt = strtxt .. '/00'
		elseif characters[currentID].attr.str.extra > 9 then
			strtxt = strtxt .. '/' .. characters[currentID].attr.str.extra
		elseif characters[currentID].attr.str.extra > 0 then
			strtxt = strtxt .. '/0' .. characters[currentID].attr.str.extra
		end
	end
	if(characters[currentID].attr.str.current > characters[currentID].attr.str.base or characters[currentID].attr.str.extra > characters[currentID].attr.str.extraBase) then
		strtxt = '^G' .. strtxt .. '^-'
	end
	if(characters[currentID].attr.str.current < characters[currentID].attr.str.base or characters[currentID].attr.str.extra < characters[currentID].attr.str.extraBase) then
		strtxt = '^R' .. strtxt .. '^-'
	end
	return strtxt
end

function updateAttrTable()
	
	statusEffects = { }
	for k, v in pairs(characters[currentID].statusEffects) do
		table.insert(statusEffects, v)
		
	end

	listItems = { }
	listTest = { }

	lastID = currentID
	helpTextString = ''
	showClassInfo = 0
	showJustText = 0
	showMemorized = 0
	showBothLists = 0
	showStats = 1
	showAbilityBonuses = 0

	otherlist = { }

	attributeItems = {
		{ characters[currentID].attr.str, 9582 },
		{ characters[currentID].attr.dex, 9584 },
		{ characters[currentID].attr.con, 9583 },
		{ characters[currentID].attr.int, 9585 },
		{ characters[currentID].attr.wis, 9586 },
		{ characters[currentID].attr.cha, 9587 }
		}


	if currentTab == 1 then
		showJustText = 1
		showStats = 0
		helpTextString = characters[currentID].proficiencies.details
	elseif currentTab == 2 then
		showClassInfo = 1
		showStats = 0
		
		listItems = {
			{ characters[currentID].classlevel.first, characters[currentID].classlevel.first },
			{ characters[currentID].classlevel.second, characters[currentID].classlevel.second },
			{ characters[currentID].classlevel.third, characters[currentID].classlevel.third },
		}
	elseif currentTab == 3 then
	
		listItems =	{
			{ characters[currentID].proficiencies.lore.strRef,  characters[currentID].proficiencies.lore.current },
			{ characters[currentID].proficiencies.reputation.strRef, characters[currentID].proficiencies.reputation.current, characters[currentID].proficiencies.reputation.helpStrRef },

		}
		for k, v in ipairs(characters[currentID].proficiencies.class_skills) do
			table.insert(listItems, {v.strRef, v.current})
			--table.insert(listItems, {v.helpStrRef, ''})
		end

		showJustText = 1
		showStats = 0
		helpTextString = ''
		for k, v in ipairs(listItems) do
			if (v[3] == nil or v[3] == '') then
				helpTextString = helpTextString .. Infinity_FetchString( v[1])  .. ': ' .. v[2] .. '^-' .. '\n'
			else
				helpTextString = helpTextString .. Infinity_FetchString( v[1])  .. ': ' .. v[2] .. '^-' .. '\n' .. Infinity_FetchString(v[3]) ..'\n \n'
			end
		end
		
	elseif currentTab == 4 then
		listItems = {	}
		showJustText = 1
		showStats = 0
		if openAdvance == 0 then
			for k, v in ipairs(listItems) do
				--Infinity_Log( 'v[2]'.. v[2])
				helpTextString = helpTextString .. '^M' .. Infinity_FetchString( v[1])  .. ': '.. v[2] .. '^-' .. '\n' .. Infinity_FetchString(v[3])  ..'\n \n'
			end
		else
			for k, v in ipairs(listItems) do				
				helpTextString = helpTextString .. '^M' .. Infinity_FetchString( v[1])  .. ': '.. v[2] .. '^-' ..'\n'
			end
		end
	elseif currentTab == 8 then
		listItems = {	}
		for k, v in ipairs(characters[currentID].proficiencies.ability) do
			table.insert(listItems, {v.strRef, v.current, v.helpStrRef})
			--table.insert(listItems, {v.helpStrRef, ''})
		end
		
		showAbilityBonuses = 1
		showJustText = 0
		showStats = 0
		for k, v in ipairs(listItems) do
			helpTextString = helpTextString .. '^M' .. v[2] .. '\n \n'
		end

	elseif currentTab == 9 then
		showJustText = 1
		showStats = 0
		helpTextString = ''
		table.insert(listItems, { 'HP_LABEL', characters[currentID].HP.current .. '/' .. characters[currentID].HP.max , characters[currentID].HP.details })
		table.insert(listItems, { 'AC_LABEL', displayCompiledAC(),  characters[currentID].AC.details })
		table.insert(listItems, { 'NUM_ATTACKS_LABEL', characters[currentID].proficiencies.numAttacks.current, '' })
		
		if characters[currentID].proficiencies.weapons.current ~= "" then
			table.insert(listItems, { 'PROFICIENCIES_LABEL', '', characters[currentID].proficiencies.weapons.current })
		end
		if characters[currentID].proficiencies.fightingstyles.current ~= "" then
			table.insert(listItems, { 'FIGHTING_STYLES_LABEL', '', characters[currentID].proficiencies.fightingstyles.current })
		end

		if ( characters[currentID].THAC0.detailsOffhand ~= nil and characters[currentID].THAC0.detailsOffhand ~= "" ) then
			table.insert(listItems, { 'MAIN_HAND_THAC0', characters[currentID].THAC0.current .. '\n' .. characters[currentID].THAC0.details .. '\n\n' .. t('OFF_HAND_THAC0')..': '..characters[currentID].THAC0.offhand .. '\n' .. characters[currentID].THAC0.detailsOffhand,  '' })
		else
			table.insert(listItems, { 'THAC0_LABEL', characters[currentID].THAC0.current,  characters[currentID].THAC0.details })
		end

		if ( characters[currentID].damage.maxOffhand ) then
			table.insert(listItems, { 'MAIN_HAND_DAMAGE', characters[currentID].damage.min .. '-' .. characters[currentID].damage.max .. '\n' .. characters[currentID].damage.details .. '\n\n' .. t('OFF_HAND_DAMAGE') .. ': ' .. characters[currentID].damage.minOffhand .. '-' .. characters[currentID].damage.maxOffhand .. '\n' .. characters[currentID].damage.detailsOffhand, ''})
		else
			table.insert(listItems, { 'DAMAGE_LABEL', characters[currentID].damage.min .. '-' .. characters[currentID].damage.max, characters[currentID].damage.details})
		end
		table.insert(listItems, { 'SAVING_THROWS_LABEL', '',  characters[currentID].proficiencies.savingThrows })
		table.insert(listItems, { 'RESISTANCES_LABEL', '',  characters[currentID].proficiencies.resistances })
		table.insert(listItems, { 'CURRENT_SCRIPT_LABEL', '',  characters[currentID].proficiencies.currentScript })

		for k, v in ipairs(listItems) do				
			if (v[3] == '' or v[3] == nil) then
				helpTextString = helpTextString ..  t(v[1])  .. ': '.. v[2] .. '^-' .. '\n\n'
			else
				helpTextString = helpTextString ..  t(v[1])  .. ': '.. v[2] .. '^-' .. '\n' .. v[3]  ..'\n\n'
			end
		end
	
	elseif currentTab == 6 then
		otherlist = { 
		{ characters[currentID].Stats.bestenemy.strRef, characters[currentID].Stats.bestenemy.current, ' ' },
		{ characters[currentID].Stats.timespent.strRef, characters[currentID].Stats.timespent.current, ' '},
		{ characters[currentID].Stats.favspell.strRef, characters[currentID].Stats.favspell.current, ' '},
		{ characters[currentID].Stats.favweapon.strRef, characters[currentID].Stats.favweapon.current, ' '},
		}
		listItems = {
		{ characters[currentID].Stats.partychapxp.strRef, characters[currentID].Stats.partychapxp.current .. '%', characters[currentID].Stats.partygamexp.current .. '%'},
		{ characters[currentID].Stats.partychapkills.strRef, characters[currentID].Stats.partychapkills.current .. '%', characters[currentID].Stats.partygamekills.current .. '%'},
		{ characters[currentID].Stats.chapxpvalue.strRef, characters[currentID].Stats.chapxpvalue.current, characters[currentID].Stats.gamexpvalue.current},
		{ characters[currentID].Stats.chapkills.strRef, characters[currentID].Stats.chapkills.current, characters[currentID].Stats.gamekills.current},
		}
	elseif currentTab == 7 then
		listItems = {	}
		showJustText = 1
		showStats = 0
		helpTextString = Infinity_FetchString(characters[currentID].biography)
	elseif currentTab == 5 then
		listItems = {	}
		showJustText = 1
		showStats = 0
		helpTextString = characters[currentID].kitDesc
	else
		listItems = { }
	end

	characterViewable = characterScreen:IsCharacterViewable()
	showClassInfo = showClassInfo == 1 and characterViewable == true
	showJustText = showJustText == 1 and characterViewable == true
	showMemorized = showMemorized == 1 and characterViewable == true
	showBothLists = showBothLists == 1 and characterViewable == true
	showStats = showStats == 1 and characterViewable == true
	showAbilityBonuses = showAbilityBonuses == 1 and characterViewable == true
end

characters = {}
statusEffects = { }

currentID = 16974083
canLevelUp = 0
openAdvance = 0
notrealValue = 0

function trunc(str, len)
	if str:len() < len then
		return str
	else
		return str:sub(1,len) .. "..."
	end
end

function characterDescString(char)
	return Infinity_FetchString(char.gender) .. "\n" .. Infinity_FetchString(char.race) .. "\n" .. char.class .. "\n" .. Infinity_FetchString(char.alignment) .. ""
end

function isStatModified(index)
	if (index == 1 ) then
		--strength
		return (characters[currentID].attr.str.current ~= characters[currentID].attr.str.base or characters[currentID].attr.str.extra ~= characters[currentID].attr.str.extraBase)
	else
		return attributeItems[index][1].current ~= attributeItems[index][1].base
	end
end

function displayAttr(index)
	str = 0
	if (index == 1 ) then
		str = displaySTR()
	else
		str = displayBuff( attributeItems[index][1].current, attributeItems[index][1].base, 1)
	end
	return str
end

function getPercent(first, second)
	tempNumber = ( first/second ) *100
	return tempNumber
end

function displayBuff( current, base, highisbetter)
	
	tmpstr = ''	
	--Infinity_Log( current .. ' - '.. base )
	if(highisbetter) then
		if(current > base) then
			tmpstr	= '^G' .. current .. '^-'
		elseif (current < base) then
			tmpstr	= '^R' .. current .. '^-'			
		end
	else
		if(current > base) then
			tmpstr	= '^R' .. current .. '^-'
		elseif (current < base) then
			tmpstr	= '^G' .. current .. '^-'			
		end
	end
	if(current == base) then
		tmpstr = current		
	end
	return tmpstr
end

function getNextLevelString()
	local nextLevelXp = characters[currentID].level.nextLvlXp - characters[currentID].level.xp
	local str = ""
	if(nextLevelXp > 0) then
		str = t("NEXT_LEVEL_LABEL")
		str = str .. " "
		str = str .. nextLevelXp
		str = str .. " "
		str = str .. t("XP_LABEL")
	else
		str = t("READY_TO_LEVEL_LABEL")
	end
	return str
	
end

function CurrentlyInGame()
	if characterScreen:IsInGame() == true then
		return true
	else
		return false
	end
end
function getClassString()
	local out = characters[currentID].classlevel.first.details
	if ( characters[currentID].classlevel.second ) then
		out = out .. '\n\n' .. characters[currentID].classlevel.second.details
	end
	if ( characters[currentID].classlevel.third ) then
		out = out .. '\n\n' .. characters[currentID].classlevel.third.details
	end

	out = out .. '\n\n' .. characters[currentID].kitDesc

	return out
end
	listItems = { }
	listTest = { }

	helpTextString = ''
	currentTabIndex = 0
	currentTab = 0
	currentItem = 0
	ShowClassInfo = 0
	showStats = 0
	showJustText = 0
	showMemorized = 0
	showBothLists = 0
	characterViewable = true
`
menu
{
	name	'CHARACTER'
	modal lua "not CurrentlyInGame()"
	align center center
	ignoreEsc
	onopen
	"
		currentTab = 1
		currentTabIndex = 1
		currentItem = 0
		showStats = 0
		showJustText = 0
		showClassInfo = 0
		showAbilityBonuses = 0
		showMemorized = 0
		showBothLists = 0
		characterViewable = true
		
		if(CurrentlyInGame()) then
			pushSidebars()
		end
		updateAttrTable()
		
		if(currentPanelID == const.EXPORT_ID) then
			Infinity_PushMenu('CHARACTER_EXPORT')
		else 
			if(currentPanelID == const.CUSTOMIZE_ID) then 
				Infinity_PushMenu('CHARACTER_CUSTOMIZE')
			else
				currentPanelID = 0
			end
		end
	"
	onclose
	"
		popSidebars()
	"

	label
	{
		area	0 0 864 709
		mosaic	"GUIREC2"
	}
	
	
	label
	{
		name		"LABEL_2_268435495"
		area		200 10 454 38
		text		lua "characters[currentID].name"
		text style  	'title'
		text align	center center
		enabled "characterViewable"
	}

	label
	{
		area		622 450 166 18
		progressbar lua "getPercent(characters[currentID].level.xp, characters[currentID].level.nextLvlXp)" --progress percentage, number 0-100
		greyscale	0 --display greyscale or not, number 0-1
		progressbar color	128 0 0 255	 --color when percentage != 100
		progressbar full	128 0 0 255	 --color when percentage == 100
		enabled "characterViewable"
	}
	label
	{
		area		622 450 166 18
		text		lua "getNextLevelString()"
		text style  'normal'
		text align	center center
		text shadow 1
		enabled "characterViewable"
	}



	button
	{
		area 78 56 140 42
		bam	'GUIOSTSM'
		text 'INFORMATION_BUTTON'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 1; updateAttrTable()"
	}
	button
	{
		area 218 56 140 42
		bam	'GUIOSTSM'
		text 'CLASS_LABEL'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 2; updateAttrTable()"
	}
	button
	{
		area 358 56 140 42
		bam	'GUIOSTSM'
		text 'COMBAT_STATS_LABEL'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 9; updateAttrTable()"
	}
	button
	{
		area 498 56 140 42
		bam	'GUIOSTSM'
		text 'SKILLS_LABEL'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 3; updateAttrTable()"
	}

	button
	{
		area 638 56 140 42
		bam	'GUIOSTSM'
		text 'ABILITIES_BUTTON'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 8; updateAttrTable()"
	}

	button
	{
		area 66 130 140 42
		bam	'GUIOSTSM'
		text 'STATS_LABEL'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 6; updateAttrTable()"
	}

	button
	{
		area 238 130 140 42
		bam	'GUIOSTSM'
		text 'BIOGRAPHY_LABEL'
		text style "button"
		pad 10 4 10 4
		action "currentTab = 7; updateAttrTable()"
	}

	list
	{
		column 
		{ 
			width 65
			label
			{
				area		0 0 -1 36 
				text		lua "Infinity_FetchString( attributeItems[rowNumber][1].strRef)"
				text style  'normal'
				text align	left center
			}
		}
		column 
		{ 
			width 35
			label
			{
				area		0 0 -1 36 
				text		lua  "displayAttr(rowNumber)" --"listItems[rowNumber][1].current"
				text style  'label'
				text align right center
				text shadow lua "isStatModified(rowNumber)"
				
			}
		}

		area 426 144 152 216
		
		rowheight	36
		table		"attributeItems"
		var			currentItem
		hidehighlight
		enabled "characterViewable"
		action
		"
			helpTextString = Infinity_FetchString( attributeItems[currentItem][2])
		"		
	}

	list
	{
		column 
		{ 
			width 13
			label
			{
				area		0 0 22 -1
				bam			lua "statusEffects[rowNumber].bam"
				sequence	lua "statusEffects[rowNumber].current"
				text align	center center				
			}
		}
		column 
		{ 
			width 87
			label
			{
				area		0 0 -1 -1
				text		lua "Infinity_FetchString(statusEffects[rowNumber].strRef)"
				text style  'normal'
				text align	left center
			}
		}

		area 420 486 164 94
		rowheight	dynamic
		table		"statusEffects"
		var		notrealValue
		scrollbar	'GUISCRC'
		enabled "characterViewable"
		hidehighlight	
	}

	button
	{
		name		"BUTTON_2_2"
		area		618 147 180 279
		--text		lua "characters[currentID].portrait"
		text align	center center
		text point	10
		text color	B
		bitmap		lua "characters[currentID].portrait"
		action
		"
			Infinity_Log(dump(characters, 0))
		"
	}
	label
	{
		area 610 492 194 92
		text lua "characterDescString(characters[currentID])"
		text style 'normal'
		text align center center
		enabled "characterViewable"
		
	}
	
	-- class section
		
	text
	{
		enabled		"showClassInfo"
		area		50 182 342 412
		text		lua "getClassString()"
		text style  'normal'
		scrollbar	'GUISCRC'
	}

	-- ability bonus stuff
	
	list
	{		
		column 
		{ 
			width 100
			label
			{
				area		0 0 -1 -1
				text		lua "listItems[rowNumber][2]" 
				text style  'normal'
				text align	left center

			}
		}

		area 50 182 342 418
		
		enabled		"showAbilityBonuses"
		rowheight	45
		table		"listItems"
		var			currentItem
		scrollbar	'GUISCRC'		
		hidehighlight
		action
		"
			--helpTextString = Infinity_FetchString( listItems[currentItem][1].helpStrRef)
		"		
	}

	-- Stats screen stuff
	list
	{		
		column 
		{ 
			width 65
			label
			{
				area		0 0 -1 -1
				text		lua "Infinity_FetchString(otherlist[rowNumber][1])" 
				text style  'normal'
				text align	left center

			}
		}
		column 
		{ 
			width 35
			label
			{
				area		0 0 -1 -1
				text		lua " otherlist[rowNumber][2]"				
				text style  'normal'
				text align	center center
			}
		}

		area 50 182 346 186
		
		enabled		"showStats"
		rowheight	45
		table		"otherlist"
		var			currentItem
		scrollbar	'GUISCRC'		
		hidehighlight
		action
		"
			--helpTextString = Infinity_FetchString( listItems[currentItem][1].helpStrRef)
		"		
	}

	label
	{
		enabled		"showStats"
		area		338 368 54 38
		text		"GAME_LABEL"
		text style  'label'
		text align	center center
	}
	label
	{
		enabled		"showStats"
		area		262 368 76 38
		text		"CHAPTER_LABEL"
		text style  'label'
		text align	center center
	}

	list
	{		
		column 
		{ 
			width 65
			label
			{
				area		0 0 -1 -1
				text		lua "Infinity_FetchString(listItems[rowNumber][1])"  --lua " '^M' .. Infinity_FetchString(listItems[rowNumber][1]) .. '^-' .. '\n'  .. trunc(Infinity_FetchString( listItems[rowNumber][3]), 140)"
				text style  'normal'
				text align	left center

			}
		}
		column 
		{ 
			width 20
			label
			{
				area		0 0 -1 -1
				text		lua " listItems[rowNumber][2]"				
				text style  'normal'
				text align	center center
				
			}
		}
		column 
		{ 
			width 15
			label
			{
				area		0 0 -1 -1
				text		lua " listItems[rowNumber][3]"				
				text style  'normal'
				text align	center center
				
			}
		}

		area 54 406 350 188
		
		enabled		"showStats"
		rowheight	45
		table		"listItems"
		var			currentItem
		scrollbar	'GUISCRC'		
		hidehighlight
		action
		"
			--helpTextString = Infinity_FetchString( listItems[currentItem][1].helpStrRef)
		"		
	}


	-- Biography section 	

	text
	{
		enabled		"showJustText"
		area		54 186 342 408
		text		lua "helpTextString"
		text style  'normal'
		text align	left top
		scrollbar	'GUISCRC'
	}

	button
	{
		enabled 	"CurrentlyInGame()"
		name		"BUTTON_2_50"
		area		73 634 239 53
		text		"CUSTOMIZE_BUTTON"
		text style "button"
		bam		GUIOSTLL
		sequence	0
		clickable lua "characterScreen:IsMultiPlayerModifyable()"
		action 
		"
			characterScreen:OnCustomizeButtonClick();
		"
	}
	button
	{
		enabled 	"CurrentlyInGame()"
		name		"BUTTON_2_36"
		area		558 634 239 53
		text		"EXPORT_BUTTON"
		text style "button"
		bam		GUIOSTLR
		sequence	0
		clickable lua "characterScreen:IsExportButtonClickable()"
		action 
		"
			characterScreen:OnExportButtonClick();
		"
	}
	
	button
	{
		enabled 	"CurrentlyInGame()"
		clickable	lua "characterScreen:IsReformPartyButtonClickable()"
		name		"BUTTON_2_51"
		area		335 637 204 44
		text		"REFORM_PARTY_BUTTON"
		text style "button"
		bam		GUIOSTLM
		sequence	3
		action		"characterScreen:OnReformPartyButtonClick();"
	}
	button
	{
		enabled 	"CurrentlyInGame()"
		name		"BUTTON_2_0"
		area		430 374 140 42
		text		"DUAL_CLASS_BUTTON"
		text style "button"
		pad 10 4 10 4
		bam	'GUIOSTSM'
		sequence	2
		clickable	lua "characterScreen:IsDualClassButtonClickable()"
		action 		
		"
			popup2Button('DUALCLASS_CONFIRMATION', 'YES_BUTTON', function() characterScreen:OnDualClassButtonClick() end, 'NO_BUTTON')
		"
	}
	button
	{
		enabled 	"CurrentlyInGame()"
		name		"BUTTON_2_37"
		area		430 422 140 42
		text		"LEVEL_UP_BUTTON"
		text style "button"
		pad 10 4 10 4
		bam		'GUIOSTSM'
		sequence	3
		clickable	lua "characterScreen:IsLevelUpButtonClickable()"
		action		" characterScreen:OnLevelUpButtonClick();"
	}
	
	button
	{
		enabled 	"CurrentlyInGame()"
		on escape
		area		811 0 53 44
		action
		"
			e:SelectEngine(worldScreen)
		"
	}

	button
	{
		enabled 	"not CurrentlyInGame()"
		area		335 637 204 44
		text		"DONE_BUTTON"
		text style 	"button"
		bam		GUIOSTLM
		sequence	3
		action		"Infinity_PopMenu()"
	}
}
menu
{
	name 'CHARACTER_CUSTOMIZE'
	align center center
	modal
	ignoreesc
	onOpen
	"
		currentPanelID = const.CUSTOMIZE_ID
	"
	label 
	{
		area 0 0 864 710
		mosaic	GUICUSTB
	}

	text
	{
		area 426 120 398 490
		text 11327 --Customize help text
		scrollbar 'GUISCRC'
		text style	normal
	}
	label
	{
		area	74 12 716 44
		text	"CUSTOMIZE_TITLE"
		text style	title
	}
	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 192 340 32		
		text style "button"
		text "APPEARANCE_BUTTON"		
		clickable lua
		"
			characterScreen:IsAppearanceButtonClickable();
		"		
		action 
		"
			characterScreen:OnAppearanceButtonClick()
		"
	}
	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 228 340 32		
		text style "button"
		text "SOUNDS_BUTTON"		
		clickable lua
		"
			characterScreen:IsAppearanceButtonClickable();
		"	
		action 
		"
			characterScreen:OnSoundsButtonClick()
		"
	}
	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 264 340 32		
		text style "button"
		text "COLORS_BUTTON"		
		clickable lua
		"
			characterScreen:IsAppearanceButtonClickable();
		"	
		action 
		"
			characterScreen:OnHairSkinButtonClick()
		"
	}
	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 300 340 32		
		text style "button"
		text "SCRIPT_BUTTON"		
		action 
		"
			characterScreen:OnScriptButtonClick()
		"
	}
	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 336 340 32		
		text style "button"
		text "BIOGRAPHY_BUTTON"		
		clickable lua
		"
			characterScreen:IsAppearanceButtonClickable();
		"
		action 
		"
			characterScreen:OnCusomizeBiographyButtonClick()
		"
	}
	button
	{
		on escape
		bam 'GUIOSTUL'
		sequence 0
		area 210 653 234 44
		text style "button"
		text	"CANCEL_BUTTON"
		action 
		"
			characterScreen:OnCancelButtonClick()
			currentPanelID = 0
			Infinity_PopMenu('CHARACTER_CUSTOMIZE')
		"
	}
	button
	{
		bam 'GUIOSTUR'
		sequence 0
		area  464 653 232 44
		text style "button"
		text "DONE_BUTTON"		
		action 
		"
			characterScreen:OnDoneButtonClick()
			currentPanelID = 0
			Infinity_PopMenu('CHARACTER_CUSTOMIZE')
		"
	}
}
`
recBioEdit = ""
recBioEditBackup = ""
`
menu
{
	name 'CHARACTER_BIOGRAPHY'
	align center center
	ignoreesc
	onOpen
	"
		recBioEditBackup = recBioEdit
		currentPanelID = 23
	"
	label
	{
		area 0 0 864 710
		mosaic	GUICUSTB
	}
	label
	{
		area 84 12 700 44
		text	"BIOGRAPHY_TITLE"
		text style	'title'
	}
	edit
	{
		name		"recBioEditArea"
		area		426 120 396 490
		var			recBioEdit
		scrollbar	'GUISCRC'
		text style	"edit"
	}

	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 192 340 32		
		text style "button"
		text	"CLEAR_BUTTON"		
		action 
		"
			recBioEdit = ''
		"
	}
	button
	{
		bam 'GUICHLNG'
		sequence 0
		area 42 228 340 32	
		text style "button"
		text "REVERT_BUTTON"		
		action 
		"
			recBioEdit = recBioEditBackup
		"
	}
		button
	{
		on escape
		bam 'GUIOSTUL'
		sequence 0
		area 210 653 234 44
		text style "button"
		text	"CANCEL_BUTTON"
		action 
		"
			characterScreen:OnCancelButtonClick()
			Infinity_PopMenu()
			currentPanelID = 17
		"
	}
	button
	{
		bam 'GUIOSTUR'
		sequence 0
		area  464 653 232 44
		text style "button"
		text "DONE_BUTTON"		
		action 
		"
			characterScreen:OnDoneButtonClick()
			Infinity_PopMenu()
			currentPanelID = 17
		"
	}
}


`
scriptList_idx = 0
showingSmartOptions = false
function formatScriptName(text)
	local i =  string.find(text, ":", #text)
	if(i) then 
		text = string.sub(text,1, i - 1)
	end
	if(#text > 35) then
		text = string.sub(text,1, 35)
		text = text .. "..."
	end
	return text
end

scriptOptions = 
{
	{'SCRIPT_ATTACK_ENEMIES_LABEL',			'SCRIPT_ATTACK_ENEMIES_DESCRIPTION',		 1, 0, 0},
	{'SCRIPT_USE_MELEE_WEAPONS_LABEL',		'SCRIPT_USE_MELEE_WEAPONS_DESCRIPTION',		 2, 0, 0},
	{'SCRIPT_USE_RANGED_WEAPONS_LABEL',		'SCRIPT_USE_RANGED_WEAPONS_DESCRIPTION',	 3, 0, 0},
	{'SCRIPT_USE_ITEMS_LABEL',				'SCRIPT_USE_ITEMS_DESCRIPTION',				 4, 0, 0},
	{'SCRIPT_USE_SPECIAL_ABILITIES_LABEL',	'SCRIPT_USE_SPECIAL_ABILITIES_DESCRIPTION',	 5, 0, 0},
	{'SCRIPT_USE_OFFENSIVE_SPELLS_LABEL',	'SCRIPT_USE_OFFENSIVE_SPELLS_DESCRIPTION',	 6, 0, 0},
	{'SCRIPT_USE_DEFENSIVE_SPELLS_LABEL',	'SCRIPT_USE_DEFENSIVE_SPELLS_DESCRIPTION',	 7, 0, 0},
	{'SCRIPT_FIND_TRAPS_LABEL',				'SCRIPT_FIND_TRAPS_DESCRIPTION',			 8, 0, 0},
	{'SCRIPT_HIDE_IN_SHADOWS_LABEL',		'SCRIPT_HIDE_IN_SHADOWS_DESCRIPTION',		 9, 0, 0},
	{'SCRIPT_SING_BATTLESONG_LABEL',		'SCRIPT_SING_BATTLESONG_DESCRIPTION',		10, 0, 0},
	{'SCRIPT_TURN_UNDEAD_LABEL',			'SCRIPT_TURN_UNDEAD_DESCRIPTION',			11, 0, 0}
}

function handleScriptOptionChange(option)
	local wasOn = scriptOptions[option][4] == 2

	if option == 2 then --Melee
		if wasOn == true then
			scriptOptions[option][4] = 0
			scriptOptions[option][5] = false
		else
			scriptOptions[option][4] = 2
			scriptOptions[option][5] = true
			scriptOptions[option+1][4] = 0
			scriptOptions[option+1][5] = false
		end
	elseif option == 3 then --Ranged
		if wasOn == true then
			scriptOptions[option][4] = 0
			scriptOptions[option][5] = false
		else
			scriptOptions[option][4] = 2
			scriptOptions[option][5] = true
			scriptOptions[option-1][4] = 0
			scriptOptions[option-1][5] = false
		end
	elseif option == 8 then --Find Traps
		if wasOn == true then
			scriptOptions[option][4] = 0
			scriptOptions[option][5] = false
		else
			scriptOptions[option][4] = 2
			scriptOptions[option][5] = true
			scriptOptions[option+1][4] = 0
			scriptOptions[option+1][5] = false
			scriptOptions[option+2][4] = 0
			scriptOptions[option+2][5] = false
			scriptOptions[option+3][4] = 0
			scriptOptions[option+3][5] = false
		end
	elseif option == 9 then --Hide
		if wasOn == true then
			scriptOptions[option][4] = 0
			scriptOptions[option][5] = false
		else
			scriptOptions[option][4] = 2
			scriptOptions[option][5] = true
			scriptOptions[option-1][4] = 0
			scriptOptions[option-1][5] = false
			scriptOptions[option+1][4] = 0
			scriptOptions[option+1][5] = false
			scriptOptions[option+2][4] = 0
			scriptOptions[option+2][5] = false
		end
	elseif option == 10 then --Sing
		if wasOn == true then
			scriptOptions[option][4] = 0
			scriptOptions[option][5] = false
		else
			scriptOptions[option][4] = 2
			scriptOptions[option][5] = true
			scriptOptions[option-2][4] = 0
			scriptOptions[option-2][5] = false
			scriptOptions[option-1][4] = 0
			scriptOptions[option-1][5] = false
			scriptOptions[option+1][4] = 0
			scriptOptions[option+1][5] = false
		end
	elseif option == 11 then --Turn
		if wasOn == true then
			scriptOptions[option][4] = 0
			scriptOptions[option][5] = false
		else
			scriptOptions[option][4] = 2
			scriptOptions[option][5] = true
			scriptOptions[option-3][4] = 0
			scriptOptions[option-3][5] = false
			scriptOptions[option-2][4] = 0
			scriptOptions[option-2][5] = false
			scriptOptions[option-1][4] = 0
			scriptOptions[option-1][5] = false
		end
	else
		scriptOptions[option][4] = toggleFrame(scriptOptions[option][4])
		if scriptOptions[option][4] == 0 then
			scriptOptions[option][5] = false
		else
			scriptOptions[option][5] = true
		end
	end
end
`
menu
{
	name 'CHARACTER_SCRIPT'
	align center center
	ignoreesc
	onOpen 
	"
		doneEnabled = characterScreen:IsDoneButtonClickable(currentID)
		currentPanelID = const.SCRIPT_ID

		showingSmartOptions = (scriptList_idx == 2)
		scriptDescription = t(scriptOptions[scriptList_idx][2])

		for index, var in pairs(scriptOptions) do
			var[5] = characterScreen:GetTempSmartScriptLocal(var[3])
			if var[5] == false then
				var[4] = 0
			else
				var[4] = 2
			end
		end
	"
	label
	{
		area 0 0 864 710
		mosaic GUICHISD
	}
	label
	{
		area 84 12 700 44
		text	"SCRIPT_TITLE"
		text style	'title'
	}
	label
	{
		area 446 468 374 140
		rectangle 0
		enabled "showingSmartOptions == true"
	}
	label
	{
		area 36 120 788 44
		text	"CURRENT_SCRIPT_LABEL"
		text style	'label'
	}
	text
	{
		area 460 480 348 120
		text lua "scriptDescription"
		scrollbar 'GUISCRC'
		text style	normal
		enabled "showingSmartOptions == true"
	}

	text
	{
		area 446 190 376 422
		text lua "scriptDescription"
		scrollbar 'GUISCRC'
		text style	normal
		enabled "showingSmartOptions == false"
	}

	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 -1 -1
				enabled "scriptList[rowNumber] ~= ''"
				text lua "formatScriptName(scriptList[rowNumber])"
				text style	"normal"
				pad 8 0 0 0
			}
			label
			{
				area -10 -10 10000 10000
				enabled "scriptList[rowNumber] == ''"
				rectangle	1
			}
		}
		area 40 194 360 414
		rowheight	18
		table		"scriptList"
		var			"scriptList_idx"
		scrollbar	'GUISCRC'
		action
		"
			showingSmartOptions = (scriptList_idx == 2)
			if scriptList[scriptList_idx] ~= '' then
				Infinity_OnScriptItemSelect(scriptList_idx - 1)
				doneEnabled = characterScreen:IsDoneButtonClickable(currentID)
			else
				scriptList_idx = 0
				scriptDescription = ''
				doneEnabled = false
			end
		"
	}

	list
	{
		
		column 
		{ 
			width 80
			label
			{
				area 10 0 -1 -1
				text lua "t( scriptOptions[rowNumber][1])"
				text style	"normal"
				text align right center
			}
		}
		column 
		{ 
			width 20
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		left center
				frame		lua "scriptOptions[rowNumber][4]"
			}
		}

		area 444 194 376 266
		
		rowheight	50
		table		"scriptOptions"
		var			selScriptOpt
		scrollbar	'GUISCRC'
		enabled 	"showingSmartOptions == true"

		action		
		"
			scriptDescription = t(scriptOptions[selScriptOpt][2])
			selectedSL = 0
			selFeedOpt = 0

			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')
				handleScriptOptionChange(selScriptOpt)
			end
		"
	}

	button
	{
		on escape
		bam 'GUIOSTUL'
		sequence 0
		area 210 653 236 44
		text style "button"
		text	"CANCEL_BUTTON"
		action 
		"
			characterScreen:OnCancelButtonClick()
			Infinity_PopMenu()
			currentPanelID = 17
		"
	}
	button
	{
		clickable lua "doneEnabled"
		bam 'GUIOSTUR'
		sequence 0
		area 464 653 236 44
		text style "button"
		text "DONE_BUTTON"		
		action 
		"
			if showingSmartOptions == true then
				for index, var in pairs(scriptOptions) do
					characterScreen:SetTempSmartScriptLocal(var[3], var[5])
				end
			end

			characterScreen:OnDoneButtonClick()
			Infinity_PopMenu()
			currentPanelID = 17
			
		"
	}
}
`
list_GUIREC_13_0_idx = 0
characterExportCharacterEdit = ""
`
menu
{
	name 'CHARACTER_EXPORT'
	align center center
	modal
	ignoreEsc
	onOpen
	"
		currentPanelID = const.EXPORT_ID;
		Infinity_FocusTextEdit('characterExportCharacterEditArea');
	"
	label 
	{
		area 0 0 864 710
		mosaic	GUICHISD
	}
	label
	{
		area	74 10 716 44
		text	"EXPORT_TITLE"
		text style	title
	}

	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "list_GUIREC_13_0[rowNumber]"
				text style "list"
			}
		}
		area 44 194 356 412
		rowheight	18
		table		"list_GUIREC_13_0"
		var			"list_GUIREC_13_0_idx"
		scrollbar	'GUISCRC'
		action
		"
			Infinity_OnCharacterItemSelect(list_GUIREC_13_0_idx - 1)
		"
	}
	label
	{
		area		164 114 332 52
		text		"EXPORT_FILENAME_LABEL"
		text style	"label"
		text color 	3
	}
	edit
	{
		name		"characterExportCharacterEditArea"
		area		440 130 310 36
		var			characterExportCharacterEdit
		text style	"edit"
		maxlines	1
		action
		"
			if(characterExportCharacterEdit:len() > 7 and key_pressed ~= 8) then				
				return 0
			else
				Infinity_UpdateCharacterRecordExportPanel()
				return 1
			end
		"

	}
	text
	{
		area 446 194 374 412
		text 10962
		text style	normal
		scrollbar 'GUISCRC'
	}
	button
	{
		bam 'GUIOSTUL'
		on escape
		sequence 0
		area 210 653 236 44
		text style "button"
		text	"CANCEL_BUTTON"
		action 
		"
			characterScreen:OnCancelButtonClick()
			Infinity_PopMenu('CHARACTER_EXPORT')
			currentPanelID = 0
		"
	}
	button
	{
		clickable	lua "characterScreen:IsDoneButtonClickable(currentID)"
		bam 'GUIOSTUR'
		sequence 0
		area  464 653 236 44
		text style "button"
		text "DONE_BUTTON"		
		action 
		"
			characterScreen:OnDoneButtonClick()
		"
	}
}
`
list_GUIREC_20_5_idx = 0
doneEnabled = 0
`
menu
{
	name 'CHARACTER_SOUND'
	align center center
	ignoreesc
	onOpen 
	"
		currentPanelID = const.SOUND_ID
		Infinity_OnSoundItemSelect(0)
		doneEnabled = characterScreen:IsDoneButtonClickable(currentID)
	"
	label
	{
		area 0 0 864 710
		mosaic GUICHISD
	}
	label
	{
		area 82 12 700 44
		text	"SOUND_TITLE"
		text style	'title'
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "getFileNameStringRef(rowNumber, list_GUIREC_20_5)"
				text style	"list"
				pad 8 0 0 0
			}
		}
		area 36 190 368 421
		rowheight	18
		table		"list_GUIREC_20_5"
		var			"list_GUIREC_20_5_idx"
		scrollbar	'GUISCRC'
		action
		"
			Infinity_OnSoundItemSelect(list_GUIREC_20_5_idx - 1)
			doneEnabled = characterScreen:IsDoneButtonClickable(currentID)
		"
	}
	text
	{
		area 446 194 378 417
		text 11315
		scrollbar 'GUISCRC'
		text style	normal
	}
	button
	{
		clickable lua "list_GUIREC_20_5_idx"
		bam 'GUIOSTCL'
		sequence 0
		area 272 120 300 44
		text style "button"
		text	"PLAY_SOUND_BUTTON"
		action 
		"	
			characterScreen:OnPlayButtonClick();			
		"
	}
	button
	{
		on escape
		bam 'GUIOSTUL'
		sequence 0
		area 210 653 236 44
		text style "button"
		text	"CANCEL_BUTTON"
		action 
		"
			characterScreen:OnCancelButtonClick()
			Infinity_PopMenu()
			currentPanelID = 17
		"
	}
	button
	{
		clickable lua "doneEnabled"
		bam 'GUIOSTUR'
		sequence 0
		area  464 653 236 44
		text style "button"
		text "DONE_BUTTON"		
		action 
		"
			characterScreen:OnDoneButtonClick()
			Infinity_PopMenu()
			currentPanelID = 17
		"
	}
}
`
function toggleFrame(curFrame)
	if curFrame == 0 then 
		return 2
	else 
		return 0
	end 
end
function getSelected(cur, my)
	if cur == my then 
		return 1
	else 
		return 0
	end 
end
function removeStoryModeOption()
	for index = 1, #toggleTitles-1, 1 do
		toggleTitles[index] = toggleTitles[index+1]
	end
	toggleTitles[#toggleTitles] = nil
end
function addStoryModeOption()
	for index = #toggleTitles, 1, -1 do
		toggleTitles[index+1] = toggleTitles[index]
	end
	toggleTitles[1] = {'DIFFICULTY_LABEL_STORYMODE',	'DIFFICULTY_DESCRIPTION_STORYMODE_BG2EE',	65, 0, 0}
end

function removeOptionFromList(list, option)
	local startingPoint = 1
	local found = false
	for index = 1, #list-1, 1 do
		if list[index][3] == option then
			startingPoint = index
			found = true
			break
		end
	end
	if found == true then
		for index = startingPoint, #list-1, 1 do
			list[index] = list[index+1]
		end
		list[#list] = nil
	end
end

toggleTitles = {
{"DIFFICULTY_LABEL_STORYMODE_MIXED",	"DIFFICULTY_DESCRIPTION_STORYMODE_BG2EE",	65, 0, 0},
{"ENABLE_CLOUD_LABEL",					"ENABLE_CLOUD_DESCRIPTION", 		60, 0, 0},
{"WORLDMAP_HIGHLIGHT_LABEL",			"WORLDMAP_HIGHLIGHT_DESCRIPTION", 	66, 0, 0},
{"MP_CHAT_LABEL",						"MP_CHAT_DESCRIPTION",				67, 0, 0},
{"GORE_LABEL",							"GORE_DESCRIPTION", 				19, 0, 0},
{"WEATHER_LABEL",						"WEATHER_DESCRIPTION", 				47, 0, 0},
{"GROUP_INFRA_LABEL",					"GROUP_INFRA_DESCRIPTION", 			42, 0, 0},
{"HEAL_ON_REST_LABEL",					"HEAL_ON_REST_DESCRIPTION", 		50, 0, 0},
{"MAX_HP_ON_LEVEL_LABEL",				"MAX_HP_ON_LEVEL_DESCRIPTION", 		55, 0, 0},
{"NO_DAMAGE_INCREASE_LABEL",			"NO_DAMAGE_INCREASE_DESCRIPTION", 	64, 0, 0},
{"AUTO_USE_MAGIC_AMMO_LABEL",			"AUTO_USE_MAGIC_AMMO_DESCRIPTION", 	68, 0, 0},
}

selectedOpt = 0
helpString = 0

ttDelaySLDR = 0
keyboardSLDR = 0
mouseSLDR = 0
difficultySLDR = 0

panelID = 8

function getDifficulty(d)
	local text = ""
	if ( d ==0 ) then
		text = t("DIFFICULTY_LABEL_EASY")
	elseif (d == 1) then
		text = t("DIFFICULTY_LABEL_NORMAL")
	elseif (d == 2) then
		text = t("DIFFICULTY_LABEL_CORERULES")
	elseif (d == 3) then
		text = t("DIFFICULTY_LABEL_HARD")
	elseif (d == 4) then
		text = t("DIFFICULTY_LABEL_INSANE")
	elseif (d == 5) then
		text = string.upper(t("MULTIPLAYER_DIFFICULTY_LABEL")).." "..t("DIFFICULTY_LABEL_LEGACYOFBHAAL")
	end
	return text
end
`

menu
{
	name	'OPTIONS_GAMEPLAY'
	align center center
	modal
	onOpen
	"
		panelID = 8
		helpString = 'GAMEPLAY_DESCRIPTION'
		selectedOpt = 0
		selectedSL = 0

		if Infinity_GetOption(59, 8) ~= 0 and toggleTitles[1][3] == 65 then
			removeStoryModeOption()
		elseif Infinity_GetOption(59, 8) == 0 and toggleTitles[1][3] ~= 65 then
			addStoryModeOption()
		end

		ttDelaySLDR = Infinity_GetOption(1, panelID)
		keyboardSLDR = Infinity_GetOption(3, panelID)
		mouseSLDR = Infinity_GetOption(2, panelID)
		difficultySLDR = Infinity_GetOption(12, panelID)
		
		for index, var in pairs(toggleTitles) do
			var[5] = Infinity_GetOption(var[3], panelID)
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
 			end
		end
 
		if Infinity_CanCloudSave() == false and (toggleTitles[1][3] == 60 or toggleTitles[2][3] == 60) then
			removeOptionFromList(toggleTitles,60)
		end
	"

	button
	{
		area	0 0 1024 768
		mosaic	GUITUTB
		action
		"
			helpString = 'GAMEPLAY_DESCRIPTION'
			selectedOpt = 0
			selectedSL = 0
		"
	}
	label
	{
		area		88 16 848 44
		text		"GAMEPLAY_TITLE"
		text style	title
	}

	list
	{
		
		column 
		{ 
			width 80
			label
			{
				area 10 0 -1 -1
				text lua "t( toggleTitles[rowNumber][1])"
				text style "normal"
				text align left center
			}
		}
		column 
		{ 
			width 20
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "toggleTitles[rowNumber][4]"
			}
		}

		area 592 152 378 356
		
		rowheight	46
		table		"toggleTitles"
		var		selectedOpt
		scrollbar	'GUISCRC'

		action		
		"
			panelID = 8
			selectedSL = 0
			helpString = toggleTitles[selectedOpt][2]

			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')

				toggleTitles[selectedOpt][4] = toggleFrame(toggleTitles[selectedOpt][4])

				if toggleTitles[selectedOpt][4] == 0 then
					toggleTitles[selectedOpt][5] = 0
				else 
					toggleTitles[selectedOpt][5] = 1
				end
			end
			if selectedOpt == 1 and toggleTitles[1][5] == 1 then
				groundItemsButtonToggle = 1
				highlightButtonToggle = 1
			end
		"
	}
	
	label
	{
		area 586 508 384 108
		rectangle 0
	}
	
	text
	{
		area		596 518 364 88
		text		lua "t(helpString)"
		text style	normal
		text align	left top
		text point	12
		scrollbar	'GUISCRC'
	}

	text
	{
		area		108 150 192 39
		text		"TOOLTIP_DELAY_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 1)"
		action 
		"
			helpString = 'TOOLTIP_DELAY_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 1
		" 
	}
	slider
	{
		area 304 150 200 39
		position "ttDelaySLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		action 
		"
			helpString = 'TOOLTIP_DELAY_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 1
		" 
	}

	text
	{
		area		108 216 192 39	
		text		"KEYBOARD_SCRLSPEED_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 2)"
		enabled "not e:IsTouchUI()"
		action 
		"
			helpString = 'KEYBOARD_SCRLSPEED_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 2
		" 
	}
	slider
	{
		area 304 216 200 40
		position "keyboardSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		enabled "not e:IsTouchUI()"
		action 
		"
			helpString = 'KEYBOARD_SCRLSPEED_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 2
		" 
	}

	text
	{
		area		108 284 192 39	
		text		"MOUSE_SCRLSPEED_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 3)"
		enabled "not e:IsTouchUI()"
		action 
		"
			helpString = 'MOUSE_SCRLSPEED_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 3
		" 
	}
	slider
	{
		area 304 284 200 40
		position "mouseSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		enabled "not e:IsTouchUI()"
		action 
		"
			helpString = 'MOUSE_SCRLSPEED_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 3
		" 
	}

	text
	{
		area		108 384 192 39
		text		"DIFFICULTY_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 4)"
		enabled "Infinity_GetOption(59, 8) == 0"
		action 
		"
			helpString = 'DIFFICULTY_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 4
		" 
	}
	slider
	{
		area 304 384 200 39
		position "difficultySLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	5
		pad 4 0 4 0
		enabled "Infinity_GetOption(59, 8) == 0 and toggleTitles[1][4] == 0"
		action 
		"
			helpString = 'DIFFICULTY_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 4
		" 
	}
	label
	{
		area		304 423 200 35	
		text		lua "getDifficulty(difficultySLDR)"
		text style	"label"
		text align	center center
		enabled "Infinity_GetOption(59, 8) == 0 and toggleTitles[1][4] == 0"
	}
	label
	{
		area		108 384 404 39
		text		lua "getDifficulty(5)"
		text style	"label"
		text align	center center
		enabled "Infinity_GetOption(59, 8) ~= 0"
	}
	--fakes for story mode
	slider
	{
		area 304 384 200 39
		position "0"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	5
		pad 4 0 4 0
		enabled "Infinity_GetOption(59, 8) == 0 and toggleTitles[1][4] ~= 0"
		action 
		"
			helpString = 'DIFFICULTY_DESCRIPTION' 
			selectedOpt = 0
			selectedSL = 4
		" 
	}
	label
	{
		area		304 423 200 35	
		text		lua "getDifficulty(0)"
		text style	"label"
		text align	center center
		enabled "Infinity_GetOption(59, 8) == 0 and toggleTitles[1][4] ~= 0"
	}
	label
	{
		area 304 384 200 35
		enabled "Infinity_GetOption(59, 8) == 0 and toggleTitles[1][4] ~= 0"
		rectangle 0
		rectangle opacity 150	
	}
	
	button
	{
		bam			GUIOSTCL
		sequence	0
		area		158 501 302 44
		text		"ASSIGN_KEYS_BUTTON"
		text style	"button"
		enabled "not e:IsTouchUI()"
		action
		"
			Infinity_PushMenu( 'OPTIONS_KEYBINDINGS' );
			selectedOpt = 0
		"
	}
	button
	{
		area		158 550 302 44
		bam			GUIOSTCL
		sequence	2
		text 		"FEEDBACK_BUTTON"
		text style	"button"
		action
		"

			Infinity_PushMenu( 'OPTIONS_FEEDBACK' );
			selectedOpt = 0
		"
	}
	button
	{
		area		158 600 302 44
		bam			GUIOSTCL
		sequence	2
		text 		"AUTO_PAUSE_BUTTON"
		text style	"button"
		action
		"
			selectedOpt = 0
			Infinity_PushMenu( 'OPTIONS_AUTOPAUSE' );
		"
	}
	button
	{
		area 252 708 236 44
		bam 'GUIOSTUL'
		sequence 0
		text 		"CANCEL_BUTTON"
		text style	"button"
		action
		"			
			Infinity_PopMenu()
		"
	}
	button
	{
		area 592 708 236 44
		bam 'GUIOSTUR'
		sequence 0
		text 		"DONE_BUTTON" -- Done
		text style	"button"
		action
		"
			panelID = 8
			Infinity_ChangeOption( 1, ttDelaySLDR, panelID)
			Infinity_ChangeOption( 3, keyboardSLDR, panelID )
			Infinity_ChangeOption( 2, mouseSLDR, panelID )
			Infinity_ChangeOption( 12, difficultySLDR + 1, panelID) -- cannot set story mode through slider

			selectedOpt = 0
			selectedSL = 0

			for index, var in pairs(toggleTitles) do
				
				Infinity_ChangeOption( var[3], var[5], panelID)
						
			end

			panelID = 8
			Infinity_PopMenu()
		"
	}

}

`
autoPauseToggles = { 
{'WEAPON_UNUSABLE_LABEL',18036, 5 , 0, 0},
{'END_OF_ROUND_LABEL',10640, 25, 0, 0},
{'ENEMY_SIGHTED_LABEL',23514, 26, 0, 0},
{'SPELL_CAST_LABEL',31872, 31, 0, 0},
{'TRAP_FOUND_LABEL',58171, 34, 0, 0}
}

characterPauseToggles = { 
{'CENTER_MEMBER_LABEL',10571, 37, 0, 0},
{'CHARACTER_HIT_LABEL',18032, 1 , 0, 0},
{'CHARACTER_INJURED_LABEL',18033, 2 , 0, 0},
{'CHARACTER_DEATH_LABEL',18034, 3 , 0, 0},
{'CHARACTER_ATTACKED_LABEL',18035, 4 , 0, 0},
{'CHARACTER_TARGET_DESTROYED',18037, 13, 0, 0},
}

selOptAP = 0

`

menu
{
	name	'OPTIONS_AUTOPAUSE'
	modal
	align center center
	onOpen
	"
		panelID = 10
		selOptAP = 0
		autopauseString = 18044
		
		for index, var in pairs(autoPauseToggles) do
			var[5] = Infinity_GetOption(var[3], panelID)
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
			end
		end
		
		for index, var in pairs(characterPauseToggles) do
			var[5] = Infinity_GetOption(var[3], panelID)
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
			end
		end
	"

	button
	{
		area 0 0 864 710
		mosaic	GUICHISD
		action
		"
			autopauseString = 18044
			selOptAP = 0
		"
	}
	label
	{
		area		94 8 674 44
		text		"AUTO_PAUSE_TITLE"
		text style	title
	}
	list
	{
		
		column 
		{ 
			width 90 
			label
			{
				area 10 0 -1 -1
				text lua "t( autoPauseToggles[rowNumber][1])"
				text style "normal"
				text align left center
			}
		}
		column 
		{ 
			width 10 
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "autoPauseToggles[rowNumber][4]"
			}
		}

		area 448 186 372 428
		
		rowheight	50
		table		"autoPauseToggles"
		var		selOptAP
		scrollbar	'GUISCRC'

		action		
		"
			selOptAPC = 0
			autopauseString = autoPauseToggles[selOptAP][2]

			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')

				autoPauseToggles[selOptAP][4] = toggleFrame(autoPauseToggles[selOptAP][4])

				if autoPauseToggles[selOptAP][4] == 0 then
					autoPauseToggles[selOptAP][5] = 0
				else 
					autoPauseToggles[selOptAP][5] = 1
				end
			end
		"
	}
	list
	{
	
		column 
		{ 
			width 90 
			label
			{
				area 10 0 -1 -1
				text lua "t( characterPauseToggles[rowNumber][1])"
				text style "normal"
				text align left center
			}
		}
		column 
		{ 
			width 10 
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "characterPauseToggles[rowNumber][4]"
			}
		}

		area 34 186 372 428
		
		rowheight	50
		table		"characterPauseToggles"
		var		selOptAPC
		scrollbar	'GUISCRC'

		action		
		"
			selOptAP = 0
			autopauseString = characterPauseToggles[selOptAPC][2]

			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')

				characterPauseToggles[selOptAPC][4] = toggleFrame(characterPauseToggles[selOptAPC][4])

				if characterPauseToggles[selOptAPC][4] == 0 then
					characterPauseToggles[selOptAPC][5] = 0
				else 
					characterPauseToggles[selOptAPC][5] = 1
				end

				--Infinity_ChangeOption(characterPauseToggles[selOptAPC][3], characterPauseToggles[selOptAPC][5], panelID )
			end
		"
	}
	
	text
	{
		area		48 116 768 50
		text		lua "Infinity_FetchString(autopauseString)"
		text style	normal
		scrollbar	'GUISCRC'
	}


	button
	{
		area 212 652 236 44
		bam 'GUIOSTUL'
		sequence 0
		text 		"CANCEL_BUTTON"
		text style	"button"
		action
		"
			panelID = 8
			helpString = 'GAMEPLAY_DESCRIPTION'
			Infinity_PopMenu()
		"
	}
	button
	{
		area 464 652 236 44
		bam 'GUIOSTUR'
		sequence 0
		text 		"DONE_BUTTON" --Done
		text style	"button"
		action
		"
			panelID = 10

			for index, var in pairs(autoPauseToggles) do
				Infinity_ChangeOption( var[3], var[5], panelID)		
			end
			for index, var in pairs(characterPauseToggles) do
				Infinity_ChangeOption( var[3], var[5], panelID)		
			end

			panelID = 8
			Infinity_PopMenu()
		"
	}	
}

`
graphicsToggles = {
{'FULL_SCREEN_LABEL',18000, 9 , 0, 0, 0},
{'HARDWARE_CURSOR_LABEL',93703, 13, 0, 0, 0},
{'SCALE_UI_LABEL',93704, 14, 0, 0, 0},
{'ZOOM_LOCK_LABEL',103188, 36, 0, 0, 0},
{'SPRITE_OUTLINE_LABEL',103189, 15, 0, 0, 0},
{'GREYSCALE_ON_PAUSE_LABEL',103190, 66, 0, 0, 0},
{'HIGHLIGHT_SPRITE_LABEL',103191, 67, 0, 0, 0},
{'DITHER_ALWAYS_LABEL',18021, 52, 0, 0, 0},
{'SHOW_HP_LABEL',103205, 53, 0, 0, 0},
{'SHOW_HEALTHBAR_LABEL',103192, 65, 0, 0, 0},
{'SHOW_BLACK_SPACE_LABEL','SHOW_BLACK_SPACE_DESCRIPTION', 69, 0, 0, 0},
{'NEAREST_NEIGHBOUR_LABEL','NEAREST_NEIGHBOUR_DESCRIPTION', 70, 0, 0, 0},
}

addedDirectx = false
function appendDirectXOption()
	if addedDirectx == false then
		dxOption = {'DIRECTX_LABEL', 103148, 68, 0, 0, 0}
		table.insert(graphicsToggles, dxOption)
		addedDirectx = true
	end
end

selectedGraphicOpt = 0

fontSizeSLDR = 0
fontSizeCancel = 0
function formatGraphicsInfoString()
	return options['Graphics']['version'] .. "\nrunning on " .. options['Graphics']['renderer'] .. "\ndriver provided by " .. options['Graphics']['vendor']
end
`

menu
{
	name	'OPTIONS_GRAPHICS'
	modal
	align center center
	onOpen
	"
		if e:HasDirectX() then
			appendDirectXOption()
		end
		panelID = 6
		helpString = 18042
		selectedGraphicOpt = 0
		selectedSL = 0
		fontSizeSLDR = Infinity_GetOption(22, panelID)
		fontSizeCancel = Infinity_GetOption(22, panelID)
		
		for index, var in pairs(graphicsToggles) do
			var[5] = Infinity_GetOption(var[3], panelID)
			var[6] = 0
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
			end
		end

		if e:IsTouchUI() then
			removeOptionFromList(graphicsToggles, 9)
			removeOptionFromList(graphicsToggles, 13)
		end
	"


	button
	{
		area 0 0 864 710
		mosaic	GUICHISD
		action
		"
			helpString = 18042
			selectedSL = 0
		"
	}

	label
	{
		area		92 10 680 44
		text		"GRAPHICS_TITLE"
		text style	title
	}

	label
	{
		area		446 186 376 264
		text		lua "formatGraphicsInfoString()"
		text style	normal
		text align	center center
	}
	
	text
	{
		area		36 272 362 44
		text		"DISPLAY_OPTIONS_LABEL"
		text style	"button"
		text align 	right center
		text highlight lua "getSelected(selectedSL, 1)"
		action
		"
			selectedGraphicOpt = 0
			selectedSL = 1
		"
	}

	list
	{
		
		column 
		{ 
			width 90
			label
			{
				area 0 0 -1 -1
				text lua "t( graphicsToggles[rowNumber][1])"
				text style "normal"
				text align right center
			}
		}
		column 
		{ 
			width 10 
			label
			{
				area		10 4 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "graphicsToggles[rowNumber][4]"
			}
		}

		area 36 316 362 296
		
		rowheight	36
		table		"graphicsToggles"
		var		selectedGraphicOpt
		scrollbar	'GUISCRC'

		action		
		"
			panelID = 6
			helpString = graphicsToggles[selectedGraphicOpt][2]
			selectedSL = 0
			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')
				graphicsToggles[selectedGraphicOpt][4] = toggleFrame(graphicsToggles[selectedGraphicOpt][4])

				if graphicsToggles[selectedGraphicOpt][4] == 0 then
					graphicsToggles[selectedGraphicOpt][5] = 0
				else 
					graphicsToggles[selectedGraphicOpt][5] = 1
				end
				graphicsToggles[selectedGraphicOpt][6] = 1
				--Infinity_ChangeOption(graphicsToggles[selectedGraphicOpt][3], graphicsToggles[selectedGraphicOpt][5], panelID )
			end
		"
	}

	label
	{
		area 446 468 380 144
		mosaic GUINOTE
	}

	text
	{
		area		458 476 364 120
		text		lua "getStringFromAmbiguousSource(helpString)"
		text style	normal
		scrollbar	'GUISCRC'
	}

	text
	{
		area		28 212 155 36
		text		"FONT_SIZE_LABEL"
		text style	"label"
		text align	right center
		text upper
		text useFontZoom 1 
		text highlight lua "getSelected(selectedSL, 2)"
		action 
		"
			helpString = 17204 
			selectedGraphicOpt = 0
			selectedSL = 2
		" 
	}

	slider
	{
		area 194 212 200 36
		position "fontSizeSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	7
		pad 4 0 4 0
		action
		"
			Infinity_ChangeOption( 22, fontSizeSLDR, 6)
			helpString = 17204 
			selectedGraphicOpt = 0
			selectedSL = 1
		"
	}

	
	button
	{
		area		210 652 236 44
		bam			GUIOSTUL
		sequence	2
		text 		"CANCEL_BUTTON"
		text style	"button"
		action
		"
			panelID = 6
			Infinity_ChangeOption( 22, fontSizeCancel, panelID)

			selectedSL = 0
			Infinity_PopMenu()
		"
	}
	button
	{
		area		464 652 236 44		
		bam			GUIOSTUR
		sequence	2
		text 		"DONE_BUTTON" --Done
		text style	"button"
		action
		"
			panelID = 6
			Infinity_ChangeOption( 22, fontSizeSLDR, panelID)

			for index, var in pairs(graphicsToggles) do
				
				if ( var[6] == 1 ) then
					Infinity_ChangeOption( var[3], var[5], panelID)
				end				
			end

			selectedSL = 0
			Infinity_PopMenu()
		"
	}
}


`
soundsToggles = {
{'CHARACTER_SUBTITLES_LABEL',18015, 5, 0, 0},
{'BATTLE_CRIES_LABEL',18013, 6, 0, 0},
{'MOVEMENT_SOUNDS_LABEL',18014, 7, 0, 0}
}
selectedsoundOpt = 0
command = {
{'ALWAYS_LABEL',0, 8, 0, 0},
{'SELDOM_LABEL',0, 9, 0, 0},
{'NEVER_LABEL',0, 10, 0, 0}
}
commandSel = 0
selectOpt = {
{'ALWAYS_LABEL',0, 58, 0, 0},
{'SELDOM_LABEL',0, 59, 0, 0},
{'NEVER_LABEL',0, 60, 0, 0}
}
selectSel = 0
ambientSLDR = 0
sfxSLDR = 0
voiceSLDR = 0
musicSLDR = 0
movieSLDR = 0

`

menu
{
	name	'OPTIONS_SOUND'
	align center center
	modal
	onOpen
	"
		panelID = 7
		helpString = 18042
		selectedsoundOpt = 0
		selectedSL = 0

		ambientSLDR = Infinity_GetOption(1, panelID)
		sfxSLDR = Infinity_GetOption(2, panelID)
		voiceSLDR = Infinity_GetOption(3, panelID)
		musicSLDR = Infinity_GetOption(4, panelID)
		movieSLDR = Infinity_GetOption(22, panelID)

		for index, var in pairs(command) do
				var[5] = Infinity_GetOption(var[3], panelID)
				if var[5] == 0 then
					var[4] = 0
				else
					var[4] = 2
					commandSel = index
				end
			end
		for index, var in pairs(selectOpt) do
			var[5] = Infinity_GetOption(var[3], panelID)
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
				selectSel = index
			end
		end
		for index, var in pairs(soundsToggles) do
			var[5] = Infinity_GetOption(var[3], panelID)
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
				selectSel = index
			end
		end
	"
	
	button
	{
		area	14 -2 1024 768
		mosaic	GUITUTB
		action
		"
			helpString = 18042
		"
	}
	label
	{
		area		102 14 848 44
		text		"SOUND_TITLE"
		text style	title
	}
	
	text
	{
		area		122 450 394 44
		text		"CHARACTER_SOUNDS_LABEL"
		text style	"button"
		text align 	right center
	}

	list
	{
		
		column 
		{ 
			width 90
			label
			{
				area 0 0 -1 -1
				text lua "t( soundsToggles[rowNumber][1])"
				text style "normal"
				text align right center
			}
		}
		column 
		{ 
			width 10 
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "soundsToggles[rowNumber][4]"
			}
		}

		area 122 500 395 150
		
		rowheight	46
		table		"soundsToggles"
		var		selectedsoundOpt
		scrollbar	'GUISCRC'

		action		
		"
			panelID = 7
			helpString = soundsToggles[selectedsoundOpt][2]
			selectedSL = 0
			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')
				soundsToggles[selectedsoundOpt][4] = toggleFrame(soundsToggles[selectedsoundOpt][4])

				if soundsToggles[selectedsoundOpt][4] == 0 then
					soundsToggles[selectedsoundOpt][5] = 0
				else 
					soundsToggles[selectedsoundOpt][5] = 1
				end
				
			end
		"
	}
	
	text
	{
		area		608 136 372 44
		text		"COMMAND_SOUNDS_BUTTON"
		text style	"button"
		text align 	right center
		text highlight lua "getSelected(selectedSL, 1)"
		action 
		"
			helpString = 18016 
			selectedsoundOpt = 0
			selectedSL = 1
		"
	}

	
	list
	{
		
		column 
		{ 
			width 90 
			label
			{
				area 10 0 -1 -1
				text lua "t( command[rowNumber][1])"
				text style	"normal"
				text align right center
			}
		}
		column 
		{ 
			width 10
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				text align 	center center
				frame		lua "command[rowNumber][4]"
			}
		}

		area 608 180 372 145
		
		rowheight	46
		table		"command"
		var		commandSel
		scrollbar	'GUISCRC'
		hidehighlight

		action		
		"
			panelID = 7
			helpString = 18016 
			selectedSL = 1
			opt = commandSel
			command[1][4] = 0
			command[2][4] = 0
			command[3][4] = 0
			selectedSoundOpt = 0
			
			Infinity_PlaySound('GAM_09')
			command[opt][4] = 2
		"
	}

	text
	{
		area		608 317 372 44
		text		"SELECTION_BUTTON"
		text style	"button"
		text align 	right center
		text highlight lua "getSelected(selectedSL, 2)"
		action 
		"
			helpString = 11352 
			selectedsoundOpt = 0
			selectedSL = 2
		"
	}

	list
	{
		
		column 
		{ 
			width 90
			label
			{
				area 10 0 -1 -1
				text lua "t( selectOpt[rowNumber][1])"
				text style	"normal"
				text align right center
			}
		}
		column 
		{ 
			width 10
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "selectOpt[rowNumber][4]"
			}
		}

		area 608 360 372 145
		
		rowheight	46
		table		"selectOpt"
		var		selectSel
		scrollbar	'GUISCRC'
		hidehighlight
		action		
		"
			panelID = 7
			helpString = 11352 
			selectedSL = 2
			opt = selectSel
			selectOpt[1][4] = 0
			selectOpt[2][4] = 0
			selectOpt[3][4] = 0
			selectedSoundOpt = 0
			
			Infinity_PlaySound('GAM_09')
			selectOpt[opt][4] = 2
		"
	}
	
	label
	{
		area 604 505 376 107
		rectangle 0
	}
	
	text
	{
		area		616 515 354 87
		text		lua "Infinity_FetchString(helpString)"
		text style	normal
		scrollbar	'GUISCRC'
	}
	
	text
	{
		area		122 136 394 44
		text		"VOLUME_CONTROLS_LABEL"
		text style	"button"
		text align 	right center
	}

	text
	{
		area		122 185 173 40
		text		"AMBIENT_VOLUME_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 4)"
		action 
		"
			helpString = 18008 
			selectedsoundOpt = 0
			selectedSL = 4
		"
	}
	slider
	{
		area 304 185 200 36
		position "ambientSLDR"
		mosaic GUISLDR
		bam	 'SLDRSTAR'
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		action 
		"
			helpString = 18008 
			selectedsoundOpt = 0
			selectedSL = 4
		"
	}

	text
	{
		area		122 240 173 40	
		text		"SFX_VOLUME_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 5)"
		action 
		"
			helpString = 18009 
			selectedsoundOpt = 0
			selectedSL = 5
		"
		
	}
	slider
	{
		area 304 240 200 36
		mosaic GUISLDR
		position "sfxSLDR"
		bam	 'SLDRSTAR'
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		action 
		"
			helpString = 18009 
			selectedsoundOpt = 0
			selectedSL = 5
		"
	}

	text
	{
		area		122 295 173 40	
		text		"VOICE_VOLUME_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 6)"
		action 
		"
			helpString = 18010 
			selectedsoundOpt = 0
			selectedSL = 6
		"
	}
	slider
	{
		area 304 295 200 36
		position "voiceSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		action 
		"
			helpString = 18010 
			selectedsoundOpt = 0
			selectedSL = 6
		"
	}

	text
	{
		area		122 350 173 40	
		text		"MUSIC_VOLUME_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 7)"
		action 
		"
			helpString = 18011 
			selectedsoundOpt = 0
			selectedSL = 7
		"
		
	}
	slider
	{
		area 304 350 200 36
		position "musicSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		text highlight lua "getSelected(selectedSL, 7)"
		action 
		"
			helpString = 18011 
			selectedsoundOpt = 0
			selectedSL = 7
		"
	}

	text
	{
		area		122 405 173 40	
		text		"MOVIE_VOLUME_LABEL"
		text style	"label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 8)"
		action 
		"
			helpString = 18012
			selectedsoundOpt = 0
			selectedSL = 8
		"
	}
	slider
	{
		area 304 405 200 40
		position "movieSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	40
		pad 4 0 4 0
		action 
		"
			helpString = 18012
			selectedsoundOpt = 0
			selectedSL = 8
		"
	}

	button
	{
		area		264 705 236 44
		bam			GUIOSTUL
		sequence	2
		text 		"CANCEL_BUTTON"
		text style	"button"
		action
		"
			selectedSL = 0
			panelID = 8
			Infinity_PopMenu()
		"
	}
	button
	{
		area		608 705 236 44		
		bam			GUIOSTUR
		sequence	2
		text 		"DONE_BUTTON"
		text style	"button"
		action
		"
			panelID = 7
			
			for index, var in pairs(command) do
				Infinity_Log('Com var[4] #' .. index .. ': ' .. var[4])
				if var[4] == 2 then
					Infinity_ChangeOption( var[3], 1, panelID)
				end
			end
			for index, var in pairs(selectOpt) do
				Infinity_Log('Sel var[4] #' .. index .. ': ' .. var[4])
				if var[4] == 2 then
					Infinity_ChangeOption( var[3], 1, panelID)	
				end	
			end
			Infinity_ChangeOption( 1, ambientSLDR, panelID)
			Infinity_ChangeOption( 2, sfxSLDR, panelID )
			Infinity_ChangeOption( 3, voiceSLDR, panelID )
			Infinity_ChangeOption( 4, musicSLDR, panelID)
			Infinity_ChangeOption( 22, movieSLDR, panelID)

			selectedOpt = 0
			selectedSL = 0

			for index, var in pairs(soundsToggles) do				
				Infinity_ChangeOption( var[3], var[5], panelID)						
			end

			panelID = 8
			Infinity_PopMenu()
		"
	}
}


`

feedbackToggles = {
{'COLORED_MARKERS_LABEL',			'COLORED_MARKERS_HELP', 			38, 0, 0},
{'CLASSIC_MARKERS_LABEL',			'CLASSIC_MARKERS_HELP', 			45, 0, 0},
{'ENABLE_CONFIRMATION_LABEL',		'ENABLE_CONFIRMATION_HELP', 		41, 0, 0},
{'DISABLE_COSMETIC_ATTACKS_LABEL',	'DISABLE_COSMETIC_ATTACKS_HELP', 	43, 0, 0},
{'JOURNAL_POPUPS_LABEL',			'JOURNAL_POPUPS_HELP', 				44, 0, 0}
}

messagesToggles = { 
{'TO_HIT_ROLLS_LABEL',		'TO_HIT_ROLLS_HELP', 	10, 0, 0},
{'ACTIONS_LABEL', 			'ACTIONS_HELP', 		12, 0, 0},
{'STATE_CHANGES_LABEL',		'STATE_CHANGES_HELP', 	13, 0, 0},
{'COMBAT_INFO_LABEL',		'COMBAT_INFO_HELP', 	11, 0, 0},
{'SELECTION_TEXT_LABEL',	'SELECTION_TEXT_HELP',	14, 0, 0},
{'MISC_LABEL',				'MISC_HELP', 			15, 0, 0}
}

selFeedOpt = 0
selMessageOpt = 0
helpString = 0

markerFeedSLDR = 0
locatorFeedSLDR = 0

function getFrequency(d,includeHighter)
	strref = ""
	if ( d ==0 ) then
		strref = "MINIMUM"
	elseif (d == 1) then
		strref = "LOW"
	elseif (d == 2) then
		strref = "MEDIUM"
	elseif (d == 3) then
		strref = "HIGH"
	elseif (d == 4 and includeHighter == true) then
		strref = "HIGHER"
	elseif (d == 4 and includeHighter == false) then
		strref = "MAXIMUM"
	elseif (d == 5) then
		strref = "MAXIMUM"
	end
	return t(strref)
end

`

menu
{
	name	'OPTIONS_FEEDBACK'
	align center center
	modal
	onOpen
	"
		panelID = 9

		helpString = 'FEEDBACK_HELP'
		selFeedOpt = 0
		selMessageOpt = 0
		selectedSL = 0

		markerFeedSLDR = Infinity_GetOption(8, panelID)
		locatorFeedSLDR = Infinity_GetOption(9, panelID)
		
		for index, var in pairs(feedbackToggles) do
				var[5] = Infinity_GetOption(var[3], panelID)
				if var[5] == 0 then
					var[4] = 0
				else
					var[4] = 2
				end
			end

		for index, var in pairs(messagesToggles) do
			var[5] = Infinity_GetOption(var[3], panelID)
			if var[5] == 0 then
				var[4] = 0
			else
				var[4] = 2
			end
		end

	"

	button
	{
		area	0 0 1024 768
		mosaic	GUITUTB
		action
		"
			helpString = 'FEEDBACK_HELP'
			selFeedOpt = 0
			selMessageOpt = 0
			selectedSL = 0
		"
	}
	label
	{
		area		130 18 768 54
		text		"FEEDBACK_TITLE"
		text style	title
	}



	label
	{
		area		100 386 407 44
		text		"VISUAL_FEEDBACK_LABEL"
		text style	"label"
		text upper
		text align 	right center
	}

	list
	{
		
		column 
		{ 
			width 90
			label
			{
				area 0 0 -1 -1
				text lua "t( feedbackToggles[rowNumber][1])"
				text style "normal"
				text align right center
			}
		}
		column 
		{ 
			width 10 
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "feedbackToggles[rowNumber][4]"
			}
		}

		area 100 430 407 220
		
		rowheight	50
		table		"feedbackToggles"
		var		selFeedOpt
		scrollbar	'GUISCRC'

		action		
		"
			selectedSL = 0
			selMessageOpt = 0
			helpString = feedbackToggles[selFeedOpt][2]

			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')
				feedbackToggles[selFeedOpt][4] = toggleFrame(feedbackToggles[selFeedOpt][4])

				if feedbackToggles[selFeedOpt][4] == 0 then
					feedbackToggles[selFeedOpt][5] = 0
				else 
					feedbackToggles[selFeedOpt][5] = 1
				end
			end
		"
	}

	label
	{
		area		586 140 380 32
		text		"FEEDBACK_MESSAGES_LABEL"
		text style	"label"
		text upper
		text align 	right center
	}

	list
	{
		
		column 
		{ 
			width 90
			label
			{
				area 10 0 -1 -1
				text lua "t( messagesToggles[rowNumber][1])"
				text style	"normal"
				text align right center
			}
		}
		column 
		{ 
			width 10
			label
			{
				area		10 8 -1 -1
				bam			ROUNDBUT
				align 		center center
				frame		lua "messagesToggles[rowNumber][4]"
			}
		}

		area 586 172 380 328
		
		rowheight	50
		table		"messagesToggles"
		var		selMessageOpt
		scrollbar	'GUISCRC'

		action		
		"

			helpString = messagesToggles[selMessageOpt][2]
			selectedSL = 0
			selFeedOpt = 0

			if(cellNumber == 2) then
				Infinity_PlaySound('GAM_09')
				messagesToggles[selMessageOpt][4] = toggleFrame(messagesToggles[selMessageOpt][4])

				if messagesToggles[selMessageOpt][4] == 0 then
					messagesToggles[selMessageOpt][5] = 0
				else 
					messagesToggles[selMessageOpt][5] = 1
				end
			end
		"
	}

	label
	{
		area 586 508 384 112
		rectangle 0
	}
	
	text
	{
		area		598 520 360 86
		text		lua "t(helpString)"
		text style	normal
		scrollbar	'GUISCRC'
	}

	text 
	{
		area		106 165 190 36
		text		"MARKER_FEEDBACK_LABEL"
		text style "label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 1)"
		action 
		"
			helpString = 'MARKER_FEEDBACK_HELP' 
			selFeedOpt = 0
			selMessageOpt = 0
			selectedSL = 1
		"
		
	}
	slider
	{
		area		300 165 200 36
		position "markerFeedSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	6
		pad 5 0 5 0
		action 
		"
			helpString = 'MARKER_FEEDBACK_HELP' 
			selFeedOpt = 0
			selMessageOpt = 0
			selectedSL = 1
		"
	}
	label
	{
		area		300 201 200 36
		text		lua "getFrequency(markerFeedSLDR,true)"
		text style	"label"
		text align	center center
	}

	text
	{
		area		106 280 190 36	
		text		"LOCATOR_FEEDBACK_LABEL"
		text style "label"
		text align	right center
		text upper
		text highlight lua "getSelected(selectedSL, 2)"
		action 
		"
			helpString = 'LOCATOR_FEEDBACK_HELP' 
			selFeedOpt = 0
			selMessageOpt = 0
			selectedSL = 2
		"
	}
	slider
	{
		area 300 280 200 36
		position "locatorFeedSLDR"
		bam	 'SLDRSTAR'
		mosaic GUISLDR
		sequence 0
		frame	 1
		settings	5
		pad 5 0 5 0
		action 
		"
			helpString = 'LOCATOR_FEEDBACK_HELP' 
			selFeedOpt = 0
			selMessageOpt = 0
			selectedSL = 2
		"
	}
	label
	{
		area		300 316 200 36
		text		lua "getFrequency(locatorFeedSLDR,false)"
		text style	"label"	
		text align	center center
	}
	button
	{
		area 252 708 236 44
		bam 'GUIOSTUL'
		sequence 0
		text 		"CANCEL_BUTTON"
		text style	"button"
		action
		"
			helpString = 'GAMEPLAY_DESCRIPTION'
			selectedSL = 0
			panelID = 8
			Infinity_PopMenu()
		"
	}
	button
	{
		area 592 708 236 44
		bam 'GUIOSTUR'
		sequence 0
		text 		"DONE_BUTTON" --Done
		text style	"button"
		action
		"
			helpString = 'GAMEPLAY_DESCRIPTION'
			panelID = 9
			Infinity_ChangeOption( 8, markerFeedSLDR, panelID)
			Infinity_ChangeOption( 9, locatorFeedSLDR, panelID )

			selectedOpt = 0
			selectedSL = 0

			for index, var in pairs(messagesToggles) do
				
				Infinity_ChangeOption( var[3], var[5], panelID)
						
			end

			for index, var in pairs(feedbackToggles) do
				
				Infinity_ChangeOption( var[3], var[5], panelID)
						
			end
			Infinity_PopMenu()
		"
	}
}

`
function getGooglePlaySignInText()
	if(Infinity_GooglePlaySignedIn() == 1) then
		return t("SIGN_OUT_BUTTON")
	else
		return t("SIGN_IN_BUTTON")
	end
end

keyCategory = 1
key = 0

function displayHelp()
	if not (key == 0) then
		return 102621
	end
	return 0
end

function formatKeyCode(number)
	local ret = ""

	if number < 127 and number > 32 then
		return string.format('%c', keybindings[keyCategory][rowNumber][6])
	end
	ret = t("SDL_" .. string.format('%d', keybindings[keyCategory][rowNumber][6]))
 
	return ret
end

function getHotkeyName(category,number)
	local ret = ""
	if category < 5 then
		ret = t(keybindings[category][number][4])
		if ret == keybindings[category][number][4] then
			ret = Infinity_FetchString(keybindings[category][number][4])
		end
	else
		ret = Infinity_FetchString(keybindings[category][number][4])
	end
	return ret
end
`
menu
{
	name	'OPTIONS_KEYBINDINGS'
	modal
	align center center
	
	button -- Background
	{
		area 0 0 864 710
		mosaic GUICHISD 
	}
	
	label -- Title
	{
		area 82 12 700 40
		text  "ASSIGN_KEYS_TITLE" 
		text style	"title"
	}
	
	label -- Instruction
	{
		area 252 60 367 42
		text  "ASSIGN_KEYS_SUBTITLE" 
		text style	"label"
	}
	label -- Contextual instruction
	{
		area 42 112 778 50
		text lua "Infinity_FetchString(displayHelp())"
		text style	"label"
	}

	list -- Key categories
	{
		column 
		{ 
			width 100 
			label
			{
				area 0 0 -1 -1
				text lua "t(keycategories[rowNumber][2])"
				text style	"normal"
				text align	center center 
			}
		}
		area 42 190 360 420
		
		rowheight	24
		table		"keycategories"
		var			keyCategory
		scrollbar	'GUISCRC'
		action
		"
			Infinity_StopKeybind()
			key = 0
		"
	}

	
	list -- Key bindings
	{
		column 
		{ 
			width 90 
			label
			{
				area 0 0 -1 -1
				text lua "getHotkeyName(keyCategory,rowNumber)"
				text style	"normal"
				align left center
			}
		}
		column 
		{ 
			width 10
			label
			{
				area 0 0 -1 -1
				text lua "formatKeyCode(keybindings[keyCategory][rowNumber][6])"
				text style	"normal"
				text upper
				text align right center 
			}
		}
		
		area 448 190 372 420
		rowheight	24
		table		"keybindings[keyCategory]"
		var			key
		scrollbar	'GUISCRC'
		action
		"
		if(key > 0) then
			Infinity_StartKeybind(key);
			keybindings[keyCategory][key][6] = 0
		end
		"
	}
	
	button
	{
		area 464 654 236 44
		bam 'GUIOSTUR'
		sequence 0
		text		"DONE_BUTTON"
		text style	"button"
		action
		"
			Infinity_StopKeybind()
			key = 0
			Infinity_PopMenu();
		"	
	}
	button
	{
		area 208 654 236 44
		bam 'GUIOSTUL'
		sequence 0
		text		"REVERT_BUTTON"
		text style	"button"
		
		action
		"
			revertKeymap();
		"	
	}
}
`
creditspage = 1
function GetCreditsTitle()
	return creditspage .. ' / ' .. #credits
end
`
menu
{
	name	'CREDITS'
	align center center
	
	label
	{
		area 0 0 1024 768
		mosaic GUISMBM
	}
	
	label
	{
		area 114 18 794 36
		text lua "GetCreditsTitle()"
		text style "title"
	}
	
	text
	{
		area 114 64 794 632
		text lua "Infinity_FetchString(credits[creditspage])"
		scrollbar	'GUISCRC'
		scrollbar func "resetScrollbar"
		text style "normal"
		text align center top
	}
	
	button
	{
		area		616 716 234 44
		bam			GUIOSTUR
		sequence	6
		text		"NEXT_BUTTON"
		text style "button"
		
		action
		"
			scrollbarReset = 1
			creditspage = creditspage + 1;
			if credits[creditspage] == nil then creditspage = 1 end
		"	
	}
	button
	{
		area		178 716 234 44
		bam			GUIOSTUL
		sequence	6
		text		"BACK_BUTTON"
		text style "button"
		
		action
		"
			scrollbarReset = 1
			creditspage = creditspage - 1;
			if credits[creditspage] == nil then creditspage = #credits end
		"	
	}
	
	button
	{
		area		412 716 204 44
		bam			GUIOSTUM
		sequence	6
		text  "DONE_BUTTON"
		text style "button"
		
		action
		"
			Infinity_PopMenu();
		"	
	}
}

`
language = 0
showsubtitles = 0
function languageDetails()
	if languages[language] ~= nil then
		return Infinity_FetchString(languages[language][2]) .. '\n'  .. Infinity_FetchString(languages[language][3])
	else
		return ""
	end
end
function findCurrentLanguage()
	local lang = Infinity_GetINIString('Language', 'Text', '')
	for k,v in pairs(languages) do
		if v[1] == lang then
			language = k
		end
	end
end
`
menu
{
	name	'OPTIONS_LANGUAGE'
	modal
	align center center
	onOpen
	"
		showsubtitles = Infinity_GetINIValue('Program Options', 'Display Subtitles', 1)
		findCurrentLanguage()
	"
	
	 button
	 {
		 area		0 0 1024 768
		 mosaic		'GUICREDT'
	 }
	
	label
	{
		area 92 10 840 44
		text "LANGUAGE_TITLE"
		text style "title"
	}
	list
	{
		column { 
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "languages[rowNumber][4]"
				text style	"normal"
				text align center center 
			}
		}
	
		area		86 138 228 466
		rowheight	24
		table		"languages"
		var			language
		scrollbar	'GUISCRC'
	}
	label
	{
		area 326 138 610 508
		fill 112 111 111 64
	}
	text
	{
		area		326 138 610 508
		text lua	"languageDetails()"
		text style	normal
		text align	center top
		scrollbar	'GUISCRC'
	}
	
	label
	{
		area		86 614 170 34
		text	"SHOW_SUBTITLES_LABEL"
		text style	"label"
		text align	right center
		text upper
	}
	label
	{
		area		86 654 850 42
		text lua 	"Infinity_FetchString(102624)"
		text style	"normal"
		text align	center center
		text upper
	}
	label
	{
		area		120 58 784 72
		text lua 	"Infinity_FetchString(102626)"
		text style	"normal"
		text align	center center
		text color 	'$'
	}
	
	button
	{
		area		282 614 32 32
		bam			ROUNDBUT
		toggle		showsubtitles
	}
	
	button
	{
		area 278 714 236 44
		bam 'GUIOSTUL'
		sequence 0
		text	"CANCEL_BUTTON"
		text style	"button"
		action
		"
			-- cancel
			for index, var in pairs(languages) do
				Infinity_Log(var[3])
			end
			Infinity_PopMenu();
		"
	}
	
	button
	{
		area 532 714 236 44
		bam 'GUIOSTUR'
		sequence 0
		text 		"DONE_BUTTON"
		text style	"button"
		action
		"
			-- done
			Infinity_SetLanguage(languages[language][1],showsubtitles)
			Infinity_PopMenu()
		"
	}
	
}
`
function restoreOverlayFromQuit()
	--restore the old overlay if applicable
	if(oldOverlayMenuName) then
		Infinity_SetOverlay(oldOverlayMenuName)
	else
		Infinity_SetOverlay(nil)
	end
end
`
menu
{
	name 'QuitMenu'
	modal
	align center center
	label -- Background
	{
		area 0 0 682 234
		mosaic GUIERR6 
	}
	label --Title
	{
		area 36 24 600 120
		text  20186
		text style	"label"
	}
	button
	{
		area		88 170 234 44
		bam			GUIOSTUL
		sequence	0
		text  "QUIT_GAME_BUTTON"
		text style	"button"
		on 			return
		action
		"
			restoreOverlayFromQuit()
			Infinity_ShutdownGame()
		"	
	}
	button
	{
		area		370 170 234 44
		bam			GUIOSTUR
		sequence	0
		text  "CANCEL_BUTTON"
		text style	"button"
		on 			escape
		action
		"
			restoreOverlayFromQuit()
			Infinity_PopMenu('QuitMenu')
		"	
	}
}

`
selectedSlot = nil
itemRequestAmt = 0

function showItemAmountRequester(slotName)
	local slot = characters[id].equipment[slotName]
	if(slot.item.count == nil) then
		Infinity_Log("Nil count in requester!")
		return
	end
	if(slot.item.count > 1) then
		selectedSlot = slotName
		popupRequester(slot.item.count, inventorySplitStack, false)
	end
end
function inventorySplitStack(cnt)
	Infinity_SplitItemStack(characters[id].equipment[selectedSlot].id, cnt,'slot_inv_' .. characters[id].equipment[selectedSlot].id)
end

function GetAbilityIdentifyString()
	if(characters[id].equipment[selectedSlot].item.identified == 0) then
		return t("IDENTIFY_BUTTON")
	end
	
	if(characters[id].equipment[selectedSlot].abilityMode == 1) then
		return t("ABILITIES_BUTTON")
	end
	
	return ""
end
requester = {}
requester.requesterMax = 0
requester.requesterFunc = nil
requester.selling = false
`
menu
{
	name 'POPUP_REQUESTER'
	align center center
	modal
	onOpen
	"
		if requester.selling == false then
			itemRequestAmt = 1
		else
			itemRequestAmt = requester.requesterMax
		end
	"
	
	label
	{
		area 0 0 465 500
		mosaic GUIERR
	}
	label
	{
		area	102 116 208 47
		text	"CHOOSE_AMT_LABEL"
		text align center center
		text style "label"
	}
	edit
	{
		area		156 216 86 48
		var			itemRequestAmt
		text style	"edit"
		align center center
		maxlines	1
		action
		"
			-- only permit numbers as letters.
			-- character limit of 4
			if((tonumber(letter_pressed) ~= nil and #tostring(itemRequestAmt) < 4) or not letter_pressed) then
				return 1
			else
				return 0
			end
		"
	}
	button
	{
		bam			GUIOSTUM
		sequence	6
		area		102 318 201 43
		text  "CANCEL_BUTTON"
		text style	"button"
		action
		"
			Infinity_PopMenu()
		"
	}	
	button
	{
		bam			GUIOSTCL
		sequence	6
		area		52 264 299 45
		text  "DONE_BUTTON"
		text style	"button"
		action
		"
			local cnt = tonumber(itemRequestAmt)
			Infinity_PopMenu()
			if(cnt and cnt > 0 and cnt <= requester.requesterMax) then
				requester.requesterFunc(cnt)
			end
		"
	}
	button
	{
		bam GUIOSW
		area 248 220 44 44
		sequence 0
		action
		"
			local amt = tonumber(itemRequestAmt)
			if(amt < requester.requesterMax) then
				itemRequestAmt = amt + 1
			end
		"
		actionHold
		"
			local amt = tonumber(itemRequestAmt)
			if(amt < requester.requesterMax) then
				itemRequestAmt = amt + 1
			end
		"
	}
	button
	{
		bam GUIOSW
		area 296 220 44 44
		sequence 1
		action
		"
			local amt = tonumber(itemRequestAmt)
			if(amt > 1) then
				itemRequestAmt = amt - 1
			end
		"
		actionHold
		"
			local amt = tonumber(itemRequestAmt)
			if(amt > 1) then
				itemRequestAmt = amt - 1
			end
		"
	}
}
`
selectedAbility = -1
function initAbilities()
	--initialize selected ability
	local i = 1
	while ( i < 4 ) do
		local ability = characters[id].equipment[selectedSlot].abilities[i]
		if(ability ~= nil) then
			if(ability.selected == 1) then
				selectedAbility = i
				return
			end
		end
		i = i + 1
	end
end
`
menu
{
	name 'ITEM_ABILITIES'
	align center center
	onOpen "initAbilities()"
	
	label
	{
		area	0 0 864 710
		mosaic	GUIMGX
	}
	label
	{
		area 73 12 725 44
		text "ITEM_ABILITIES_TITLE"
		text style	"title"
	}
	text
	{
		area 180 202 496 52
		text highlight lua "selectedAbility == 1"
		enabled "characters[id].equipment[selectedSlot].abilities[1] ~= nil"
		text lua "characters[id].equipment[selectedSlot].abilities[1].text"
		text style	"label"
		action "selectedAbility = 1"
	}
	button
	{
		area 180 202 52 52
		bam "STONSLOT"
		enabled "characters[id].equipment[selectedSlot].abilities[1] ~= nil"
		icon lua "characters[id].equipment[selectedSlot].abilities[1].icon"
		action "selectedAbility = 1"
	}

	
	text
	{
		area 180 266 496 52
		text highlight lua "selectedAbility == 2"
		enabled "characters[id].equipment[selectedSlot].abilities[2] ~= nil"
		text lua "characters[id].equipment[selectedSlot].abilities[2].text"
		text style	"label"
		action "selectedAbility = 2"
	}
	button
	{
		area 180 266 52 52
		bam "STONSLOT"
		enabled "characters[id].equipment[selectedSlot].abilities[2] ~= nil"
		icon lua "characters[id].equipment[selectedSlot].abilities[2].icon"
		action "selectedAbility = 2"
	}

	text
	{
		area 180 330 496 52
		text highlight lua "selectedAbility == 3"
		enabled "characters[id].equipment[selectedSlot].abilities[3] ~= nil"
		text lua "characters[id].equipment[selectedSlot].abilities[3].text"
		text style	"label"
		action "selectedAbility = 3"
	}
	button
	{
		area 180 330 52 52
		bam "STONSLOT"
		enabled "characters[id].equipment[selectedSlot].abilities[3] ~= nil"
		icon lua "characters[id].equipment[selectedSlot].abilities[3].icon"
		action "selectedAbility = 3"
	}
	
	label
	{
		area 268 552 344 128
		text 11322
		text style "label"
	}
	
	button
	{
		area 572 636 232 44
		bam			GUIOSTUR
		text "DONE_BUTTON"
		text style "button"
		action
		"
			local itemNum = characters[id].equipment[selectedSlot].abilities[selectedAbility].itemNum
			Infinity_SelectItemAbility(selectedAbility - 1, itemNum, characters[id].equipment[selectedSlot].id)
			Infinity_PopMenu()
		"
	}
	
	button
	{
		area 54 636 232 44
		bam			GUIOSTUL
		text "CANCEL_BUTTON"
		text style "button"
		action
		"
			Infinity_PopMenu()
		"
	}

}
`
TEXT_popup_info = 0
`
menu
{
	name 'POPUP_INFO'
	align center center
	modal
	label
	{
		area 0 0 408 418
		mosaic GUIERR
	}
	label
	{
		area 70 78 258 84
		text lua "getStringFromAmbiguousSource(TEXT_popup_info)"
		text style	"label"
	}
	button
	{
		area 104 318 200 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style	"button"
		action 
		"
			Infinity_PopMenu()
		"
	}
}
menu
{
	name 'POPUP_TWOBUTTON'
	align center center
	modal
	label
	{
		area 0 0 406 415
		mosaic 'GUIERR'

	}
	label
	{
		area 70 86 264 76
		text lua "getStringFromAmbiguousSource(Popup2Button.info)"
		text style	"label"
		text align center center
	}
	button
	{
		area 52 218 302 44
		bam GUIOSTCL
		align center center
		text lua "t(Popup2Button.cancelText or 'CANCEL_BUTTON')"
		text style	"button"
		action 
		"
			Infinity_PopMenu('POPUP_TWOBUTTON')
			if (Popup2Button.cancelFunc) then
				Popup2Button.cancelFunc()
			end
		"
	}
	button
	{
		area 52 266 302 44
		bam GUIOSTCL
		align center center
		text style	"button"
		text lua "t(Popup2Button.okText or 'DONE_BUTTON')"
		action 
		"
			Infinity_PopMenu('POPUP_TWOBUTTON')
			if (Popup2Button.okFunc) then
				Popup2Button.okFunc()
			end
		"
	}
}

menu
{
	name 'POPUP_THREEBUTTON'
	align center center
	modal
	label
	{
		area 0 0 406 415
		mosaic 'GUIERR'

	}
	label
	{
		area 74 68 254 94
		text lua "getStringFromAmbiguousSource(Popup3Button.info)"
		text style	"label"
		text align center center
	}
	button
	{
		area 52 218 308 44
		bam GUIOSTCL
		align center center
		text lua "t(Popup3Button.rightText)"
		text style	"button"
		action 
		"
			Infinity_PopMenu()
			if (Popup3Button.rightFunc) then
				Popup3Button.rightFunc()
			end
		"
	}
	button
	{
		area 52 266 308 44
		bam GUIOSTCL
		align center center
		text style	"button"
		text lua "t(Popup3Button.midText)"
		action 
		"
			Infinity_PopMenu()
			if (Popup3Button.midFunc) then
				Popup3Button.midFunc()
			end
		"
	}
	button
	{
		area 103 320 200 44
		bam GUIOSTLM
		align center center
		text style	"button"
		text lua "t(Popup3Button.leftText)"
		action 
		"
			Infinity_PopMenu()
			if (Popup3Button.leftFunc) then
				Popup3Button.leftFunc()
			end
		"
	}
}

menu
{
	name 'POPUP_FOURBUTTON'
	align center center
	modal
	label
	{
		area 0 0 900 234
		mosaic GUIERR7
	}
	label
	{
		area 55 21 789 126
		text lua "getStringFromAmbiguousSource(Popup4Button.info)"
		text style	"label"
		text align center center
	}
	button
	{
		area 656 170 204 44
		bam		GUIOSTLM
		text lua "t(Popup4Button.farRightText)"
		text style	"button"
		action 
		"
			Infinity_PopMenu()
			if (Popup4Button.farRightFunc) then
				Popup4Button.farRightFunc()
			end
		"
	}
	button
	{
		area 448 170 204 44
		bam		GUIOSTLM
		text style	"button"
		text lua "t(Popup4Button.rightText)"
		action 
		"
			Infinity_PopMenu()
			if (Popup4Button.rightFunc) then
				Popup4Button.rightFunc()
			end
		"
	}
	button
	{
		area 242 170 204 44
		bam		GUIOSTLM
		text style	"button"
		text lua "t(Popup4Button.leftText)"
		action 
		"
			Infinity_PopMenu()
			if (Popup4Button.leftFunc) then
				Popup4Button.leftFunc()
			end
		"
	}
	button
	{
		area 38 170 204 44
		bam		GUIOSTLM
		text style	"button"
		text lua "t(Popup4Button.farLeftText)"
		action 
		"
			Infinity_PopMenu()
			if (Popup4Button.farLeftFunc) then
				Popup4Button.farLeftFunc()
			end
		"
	}
}

menu
{
	name 'ITEM_IDENTIFY'
	align center center
	label
	{
		area 0 0 408 418
		mosaic GUIERR
	}
	text 
	{
		area 82 74 242 88
		text 19394
		text style "label"
		align center center
	}
	button
	{
		area 52 258 302 44
		bam GUIOSTCL
		text style "button"
		text "SPELL_BUTTON"
		
		clickable lua "Infinity_GetSpellIdentifyEnabled(characters[id].equipment[selectedSlot].id)"
		action 
		"
			Infinity_OnSpellIdentify(characters[id].equipment[selectedSlot].id); 
			Infinity_PopMenu()
			itemDesc.item = characters[id].equipment[selectedSlot].item --update itemDesc item
		"
	}
	button
	{
		area 102 318 200 44
		bam GUIOSTUM
		text style "button"
		text "CANCEL_BUTTON"
		action
		"
			Infinity_PopMenu()
			if(createCharScreen:GetEngineState() == 7) then
				--If we're in import character mode, go back to the import screen.
				e:SelectEngine(startEngine)
				startEngine:OnImportCharacterButtonClick()
			end
		"
	}
	button
	{
		area 52 214 302 44
		bam GUIOSTCL
		text style "button"
		text "SCROLL_BUTTON"
		
		clickable lua "Infinity_GetScrollIdentifyEnabled(characters[id].equipment[selectedSlot].id)"
		action 
		"
			Infinity_OnScrollIdentify(characters[id].equipment[selectedSlot].id)
			Infinity_PopMenu()
			itemDesc.item = characters[id].equipment[selectedSlot].item --update itemDesc item
		"
	}
	
	
}
`
function showItemDescriptionInventory(slotName)
	if(characters[id].equipment[slotName].empty ~= 0) then
		return
	end
	
	selectedSlot = slotName
	
	Infinity_CheckItemIdentify(characters[id].equipment[slotName].id)
	showItemDescription(characters[id].equipment[slotName].item, 0)
end

itemDesc = {}
function showItemDescription(item, mode)
	itemDesc.item = item
	itemDesc.mode = mode
	Infinity_PushMenu('ITEM_DESCRIPTION',0,0)
end

function itemDescLeftButtonEnabled()
	if(itemDesc.mode == 0) then
		return GetAbilityIdentifyString() ~= ""
	elseif(itemDesc.mode == 1) then
		return itemDesc.item.isBag
	end
	return 0
end
function itemDescLeftButtonText()
	if(itemDesc.mode == 0) then
		return GetAbilityIdentifyString()
	elseif(itemDesc.mode == 1) then
		return t('OPEN_CONTAINER_BUTTON')
	end
	return ""
end
function itemDescLeftButtonAction()
	if(itemDesc.mode == 0) then
		if(characters[id].equipment[selectedSlot].item.identified == 0) then
			Infinity_PushMenu('ITEM_IDENTIFY',0,0)
		else
			Infinity_PushMenu('ITEM_ABILITIES',0,0)
		end
	elseif(itemDesc.mode == 1) then 
		storeScreen:OpenBag(itemDesc.item.res)
		Infinity_PopMenu()
	end
end

function itemDescRightButtonEnabled()
	if(itemDesc.mode == 0) then
		return characters[id].equipment[selectedSlot].useMode ~= -1
	else
		return 0
	end
end
function itemDescRightButtonText()
	return Infinity_GetUseButtonText(characters[id].equipment[selectedSlot].id, characters[id].equipment[selectedSlot].useMode)
end
function itemDescRightButtonAction()
	Infinity_PopMenu()
	Infinity_OnUseButtonClick(characters[id].equipment[selectedSlot].id, characters[id].equipment[selectedSlot].useMode)
end
`
menu
{
	name 'ITEM_DESCRIPTION'
	align center center
	modal
	label
	{
		area 0 0 864 710
		mosaic GUIINVHI
	}
	label
	{
		area 81 11 700 44
		text "ITEM_TITLE"
		text style title
	}
	label
	{
		area 402 66 52 52
		icon lua "itemDesc.item.icon"
	}
	label
	{
		area 57 170 295 40
		text lua "itemDesc.item.name"
		text align center center
		text style "label"
		text color '5'
	}
	text
	{
		area 356 180 430 353
		text lua "itemDesc.item.description"
		scrollbar 'GUISCRC'
		text style "normal_parchment"
	}
	label
	{
		area 66 210 280 327
		bam lua "itemDesc.item.descPicture"
		sequence 0
		frame 0
		align center center
	}
	button
	{
		bam			GUIOSTUL
		sequence	6
		area		57 638 234 44
		enabled "itemDescLeftButtonEnabled()"
		text lua "itemDescLeftButtonText()"
		text style "button"
		action
		"
			itemDescLeftButtonAction()
		"
	}
	button
	{
		bam			GUIOSTUM
		sequence	6
		area		326 638 204 44
		text  "DONE_BUTTON"
		text style "button"
		action
		"
			Infinity_PopMenu();
		"
	}
	button
	{
		bam			GUIOSTUR
		sequence	6
		area		572 638 234 44
		enabled "itemDescRightButtonEnabled()"
		text lua "itemDescRightButtonText()"
		text style "button"
		action
		"
			itemDescRightButtonAction()
		"
	}
}
`
function highlightSidebarButton(engine)
	return (engine == e:GetActiveEngine())
end
sidebarVisible =
{
	LEFT = 1,
	RIGHT = 1
}
function toggleSidebar(side)
	local show = side .. "_SIDEBAR"
	local hide = show .. "_HIDDEN"
	if(sidebarVisible[side] == 1) then
		local temp = show
		show = hide
		hide = temp
		sidebarVisible[side] = 0
	else
		sidebarVisible[side] = 1
	end
	Infinity_PushMenu(show)
	Infinity_PopMenu(hide)
end
sidebarForceTooltips = 0
`
menu
{
	name 'LEFT_SIDEBAR'
	align left top
	ignoreEsc
	onOpen 
	"
		if(sidebarVisible.LEFT == 1) then
			Infinity_PushMenu('LEFT_SIDEBAR_BOTTOM')
		else
			Infinity_PopMenu('LEFT_SIDEBAR')
			Infinity_PushMenu('LEFT_SIDEBAR_HIDDEN')
		end
		if(showJournal == 1) then
			Infinity_PushMenu('JOURNAL')
		end
		sidebarForceTooltips = 0
	"
	onClose 
	"
		Infinity_PopMenu('LEFT_SIDEBAR_BOTTOM')
		Infinity_PopMenu('JOURNAL')
	"
	label
	{
		name 'leftSidebarBackground'
		area 0 0 80 1536
		mosaic GUIWLSP
	}
	label
	{

		area 0 1536 80 1536
		mosaic GUIWLSP
	}
	button
	{
		area 3 14 73 55
		bam GUILS10
		sequence 0
		tooltip lua "getTooltipWithHotkey(2,16313)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
--		glow lua "highlightSidebarButton(worldScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(0)
		"
	}
	button
	{
		area 3 69 73 55
		bam GUILS10
		sequence 1
		tooltip lua "getTooltipWithHotkey(4,15418)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(mapScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(1)
		"
	}
	button
	{
		area 3 124 73 55
		bam GUILS10
		sequence 2
		tooltip lua "getTooltipWithHotkey(3,16308)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "showJournal == 1"
		clickable lua "sidebarsGreyed ~= 1 and game:GetJournalOpenable()"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(2)
		"
	}
	button
	{
		area 3 179 73 55
		bam GUILS10
		sequence 3
		tooltip lua "getTooltipWithHotkey(0,16307)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(inventoryScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(3)
		"
	}
	button
	{
		area 3 234 73 55
		bam GUILS10
		sequence 4
		tooltip lua "getTooltipWithHotkey(1,16306)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(characterScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(4)
		"
	}
	button
	{
		area 3 289 73 55
		bam GUILS10
		sequence 5
		tooltip lua "getTooltipWithHotkey(5,16309)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(mageScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(5)
		"
	}
	button
	{
		area 3 344 73 55
		bam GUILS10
		sequence 6
		tooltip lua "getTooltipWithHotkey(6,14930)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(priestScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(6)
		"
	}
	button
	{
		area 3 399 73 55
		bam GUILS10
		sequence 7
		tooltip lua "getTooltipWithHotkey(7,16311)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(optionsScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(7)
		"
	}
	button
	{
		area 3 454 73 55
		enabled "e:IsMultiplayer()"
		bam GUILS10
		sequence 8
		tooltip lua "getTooltipWithHotkey(8,16312)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		glow lua "highlightSidebarButton(multiplayerScreen)"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(8)
		"
	}

	button
	{
		area 6 0 67 16
		bam GUIPNL10
		action
		"
			toggleSidebar('LEFT')
		"
	}
}
menu
{
	name 'LEFT_SIDEBAR_BOTTOM'
	align left bottom
	offset 0 -22
	--combined height of these buttons makes a menu with height = 231, menu is placed into lower left. y pos is offset from top of this menu.
	ignoreEsc
	button
	{
		area 3 0 73 55
		enabled "worldScreen == e:GetActiveEngine()"
		bam GUILS10
		sequence 15
		tooltip lua "getTooltipWithHotkey(28,74261)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			worldScreen:OnQuickSaveButtonClick(false)
		"
		actionAlt
		"
			worldScreen:OnQuickSaveButtonClick(true)
		"
	}
	button
	{
		area 3 56 73 55
		enabled "worldScreen == e:GetActiveEngine()"
		bam GUILS10
		sequence 16
		tooltip lua "Infinity_FetchString(74270)" --"getTooltipWithHotkey(16,74270)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			Infinity_PushMenu('HELP')
		"
	}
	button
	{
		area 3 110 73 55
		bam GUILS10
		sequence 9
		tooltip lua "getTooltipWithHotkey(31,11942)"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			e:GetActiveEngine():OnRestButtonClick()
		"
	}
	
	
	--begin clock
	label
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		bam "CGEAR"
		frame lua "timer:GetCurrentTime() % 24"
		useOverlayTint "worldScreen:CheckIfPaused()"
		overlayTint 180 180 180
	}
	label
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		bam "CDIAL"
		frame lua "timer:GetCurrentHour() % timer.TIMESCALE_HOUR_PER_DAY"
		useOverlayTint "worldScreen:CheckIfPaused()"
		overlayTint 180 180 180
	}
	label
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		bam "CPEN"
		frame lua "timer:GetCurrentTime() % 24"
		useOverlayTint "worldScreen:CheckIfPaused()"
		overlayTint 180 180 180
	}
	button
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		tooltip lua "worldScreen:GetCurrentTimeString()"
		tooltip force lua "sidebarForceTooltips == 1"
		tooltip force top
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			worldScreen:TogglePauseGame(true)
		"
	}
	--end clock
	label
	{
		--area is preset
		enabled "gameOptions.m_bRenderFrameTimes"
		frameTimes
	}
}
menu
{
	name 'LEFT_SIDEBAR_HIDDEN'
	align left top
	ignoreEsc
	button
	{
		area 6 0 67 16
		bam GUIPNL10
		action
		"
			toggleSidebar('LEFT')
		"
	}
}
`
	mouseOverPortrait = -1
	draggedPortrait = nil
	function swapPortraits(dest)
		worldScreen:SwapPortraits(dest,draggedPortrait)
		draggedPortrait = nil
	end

	function getPartyAITooltip()
		if aiButtonToggle == 1 then
			return Infinity_FetchString(15918)
		else
			return Infinity_FetchString(15917)
		end
	end
`
menu
{
	name 'RIGHT_SIDEBAR'
	align right top
	ignoreEsc
	onOpen 
	"
		if(sidebarVisible.RIGHT == 1) then
			Infinity_PushMenu('RIGHT_SIDEBAR_BOTTOM')
		else
			Infinity_PopMenu('RIGHT_SIDEBAR')
			Infinity_PushMenu('RIGHT_SIDEBAR_HIDDEN')
		end
		if(worldScreen == e:GetActiveEngine() and game:GetPartyAI()) then aiButtonToggle = 1 end
		if(worldScreen == e:GetActiveEngine()) then Infinity_PushMenu('WORLD_LEVEL_UP_BUTTONS') end
	"
	onClose
	"
		Infinity_PopMenu('RIGHT_SIDEBAR_BOTTOM')
		Infinity_PopMenu('WORLD_LEVEL_UP_BUTTONS')
	"
	label
	{
		name 'rightSidebarBackground'
		area 0 0 80 1536
		mosaic GUIWRSP
	}
	label
	{
		area 0 1536 80 1536
		mosaic GUIWRSP
	}
	button
	{
		area 11 14 64 90
		portrait 0
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 0"
		glow lua "draggedPortrait and draggedPortrait ~= 0"
		action "Infinity_OnPortraitLClick(0)"
		actionAlt "Infinity_OnPortraitRClick(0)"
		actionDbl "Infinity_OnPortraitDblClick(0)"
		actiondrag "Infinity_SwapWithPortrait(0)"
		actionEnter "mouseOverPortrait = 0"
		actionExit "mouseOverPortrait = -1"
		actionSimpleDrag "draggedPortrait = 0"
		actionSimpleDrop "swapPortraits(0)"
		tooltip lua "Infinity_GetPortraitTooltip(0)"
		clickable lua "sidebarsGreyed ~= 1"
	}
	button
	{
		area 11 106 64 90
		portrait 1
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 1"
		glow lua "draggedPortrait and draggedPortrait ~= 1"
		action "Infinity_OnPortraitLClick(1)"
		actionAlt "Infinity_OnPortraitRClick(1)"
		actionDbl "Infinity_OnPortraitDblClick(1)"
		actiondrag "Infinity_SwapWithPortrait(1)"
		actionEnter "mouseOverPortrait = 1"
		actionExit "mouseOverPortrait = -1"
		actionSimpleDrag "draggedPortrait = 1"
		actionSimpleDrop "swapPortraits(1)"
		tooltip lua "Infinity_GetPortraitTooltip(1)"
		clickable lua "sidebarsGreyed ~= 1"
	}
	button
	{
		area 11 198 64 90
		portrait 2
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 2"
		glow lua "draggedPortrait and draggedPortrait ~= 2"
		action "Infinity_OnPortraitLClick(2)"
		actionAlt "Infinity_OnPortraitRClick(2)"
		actionDbl "Infinity_OnPortraitDblClick(2)"
		actiondrag "Infinity_SwapWithPortrait(2)"
		actionEnter "mouseOverPortrait = 2"
		actionExit "mouseOverPortrait = -1"
		actionSimpleDrag "draggedPortrait = 2"
		actionSimpleDrop "swapPortraits(2)"
		tooltip lua "Infinity_GetPortraitTooltip(2)"
		clickable lua "sidebarsGreyed ~= 1"
	}
	button
	{
		area 11 290 64 90
		portrait 3
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 3"
		glow lua "draggedPortrait and draggedPortrait ~= 3"
		action "Infinity_OnPortraitLClick(3)"
		actionAlt "Infinity_OnPortraitRClick(3)"
		actionDbl "Infinity_OnPortraitDblClick(3)"
		actiondrag "Infinity_SwapWithPortrait(3)"
		actionEnter "mouseOverPortrait = 3"
		actionExit "mouseOverPortrait = -1"
		actionSimpleDrag "draggedPortrait = 3"
		actionSimpleDrop "swapPortraits(3)"
		tooltip lua "Infinity_GetPortraitTooltip(3)"
		clickable lua "sidebarsGreyed ~= 1"
	}
	button
	{
		area 11 382 64 90
		portrait 4
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 4"
		glow lua "draggedPortrait and draggedPortrait ~= 4"
		action "Infinity_OnPortraitLClick(4)"
		actionAlt "Infinity_OnPortraitRClick(4)"
		actionDbl "Infinity_OnPortraitDblClick(4)"
		actiondrag "Infinity_SwapWithPortrait(4)"
		actionEnter "mouseOverPortrait = 4"
		actionExit "mouseOverPortrait = -1"
		actionSimpleDrag "draggedPortrait = 4"
		actionSimpleDrop "swapPortraits(4)"
		tooltip lua "Infinity_GetPortraitTooltip(4)"
		clickable lua "sidebarsGreyed ~= 1"
	}
	button
	{
		area 11 474 64 90
		portrait 5
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 5"
		glow lua "draggedPortrait and draggedPortrait ~= 5"
		action "Infinity_OnPortraitLClick(5)"
		actionAlt "Infinity_OnPortraitRClick(5)"
		actionDbl "Infinity_OnPortraitDblClick(5)"
		actiondrag "Infinity_SwapWithPortrait(5)"
		actionEnter "mouseOverPortrait = 5"
		actionExit "mouseOverPortrait = -1"
		actionSimpleDrag "draggedPortrait = 5"
		actionSimpleDrop "swapPortraits(5)"
		tooltip lua "Infinity_GetPortraitTooltip(5)"
		clickable lua "sidebarsGreyed ~= 1"
	}
	button
	{
		area 10 0 67 16
		bam GUIPNL10
		action
		"
			toggleSidebar('RIGHT')
		"
	}
}
menu
{
	name 'RIGHT_SIDEBAR_BOTTOM'
	align right bottom
	ignoreEsc
	--Buttons form a menu aligned bottom right, with height = 197, y is offset from top of that menu.
	button
	{
		area 6 0 71 48
		enabled "e:IsTouchUI() and worldScreen == e:GetActiveEngine()"
		toggle selectionButtonToggle
		bam GUILS10
		sequence 14
		tooltip lua "Infinity_FetchString(11942)"
		tooltip force lua "sidebarForceTooltips == 1"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			worldScreen:OnSelectionButtonClick()
		"
	}
	button
	{
		area 6 49 71 48
		enabled "worldScreen == e:GetActiveEngine()"
		toggle highlightButtonToggle
		bam GUILS10
		sequence 11
		tooltip lua "Infinity_FetchString(103144)"
		tooltip force lua "sidebarForceTooltips == 1"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			worldScreen:SetHighlightEnabled(highlightButtonToggle == 1)
		"
	}
	button
	{
		area 6 99 71 48
		enabled "worldScreen == e:GetActiveEngine()"
		toggle aiButtonToggle
		bam GUILS10
		sequence 10
		tooltip lua "getPartyAITooltip()"
		tooltip force lua "sidebarForceTooltips == 1"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			game:ToggleAI()
		"
	}
	button
	{
		area 6 149 71 48
		enabled "worldScreen == e:GetActiveEngine()"
		bam GUILS10
		sequence 13
		tooltip lua "Infinity_FetchString(10485)"
		tooltip force lua "sidebarForceTooltips == 1"
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			game:SelectAll()
		"
		actionDbl
		"
			game:CenterOnGroupLeader()
		"
	}
--	Add Button to Open-Close Cheats Console for BG2EE
	button
	{
		area -79 150 71 48
--		area -64 150 71 48
		enabled "worldScreen == e:GetActiveEngine()"
--		toggle highlightSidebarButton
		tooltip lua "'Cheat Console'"
		bam GUILS10
		sequence 2
		clickable lua "sidebarsGreyed ~= 1"
		action
		"
			Infinity_PushMenu('cheatConsole')
			Infinity_PopMenu('WORLD_ACTIONBAR')
		"
		actionAlt
		"
			Infinity_PopMenu('cheatConsole')
			Infinity_PushMenu('WORLD_ACTIONBAR')
		"
	}
}
menu
{
	name 'RIGHT_SIDEBAR_HIDDEN'
	align right top
	ignoreEsc
	button
	{
		area 10 0 67 16
		bam GUIPNL10
		action
		"
			toggleSidebar('RIGHT')
		"
	}
}
`
	TEXT_inventoryError = ""

function resetStatsDisplay()
	tempStats = {}
end
function getTempDamage()
	local str = ""
	local dmgMinTemp = getTempStat(characters[id].damage.min,'dmgMin',1)
	local dmgMaxTemp = getTempStat(characters[id].damage.max,'dmgMax',1)
	if(dmgMinTemp == "-" and dmgMaxTemp == "-") then
		return "-"
	end
	if(dmgMinTemp == "-") then
		str = characters[id].damage.min
	else
		str = dmgMinTemp
	end
	str = str .. " - "
	if(dmgMaxTemp == "-") then
		str = str .. characters[id].damage.max
	else
		str = str .. dmgMaxTemp
	end

	return str
end
function getStat(old, newName, coeff)
	return old
end
function getTempStat(old, newName, coeff)
	if(tempStats[id] == nil) then
		return "-"
	end
	local new = tempStats[id][newName]
	local score = coeff * (new - old)
	if(score == 0) then
		return "-"
	end
	if(score < 0) then
		return "^R" .. new .. "^-"
	end
	if(score > 0) then
		return "^G" .. new .. "^-"
	end
end
function checkDoubleClickScheduled(slotName)
	if(doubleClickEventScheduled == slotName) then
		slotDoubleClick(doubleClickEventScheduled, true)
		doubleClickEventScheduled = nil
	end
end
function getStatsTitle()
	if(tempStats[id] ~= nil) then
		return tempStats[id].tempItem
	else
		return ""
	end
end
function slotDoubleClick(slotName, force)
	local slot = characters[id].equipment[slotName]
	
	if(string.sub(slotName,1,6) == "ground" and force == nil) then
		--this hack is needed because the unlike other slots, ground item add/remove is a message (doesnt get executed immediately)
		--since the double click removes the item before re-adding it, we need to wait for that re-add to complete before continuing.
		doubleClickEventScheduled = slotName
		return
	end
	
	if(slot ~= nil) then
		if(slot.item.isBag ~= 0) then
			Infinity_OpenInventoryContainer(slot.item.res)
		else
			showItemAmountRequester(slotName)
		end
	end
end
function checkDoubleClickScheduled(slotName)
	if(doubleClickEventScheduled == slotName) then
		slotDoubleClick(doubleClickEventScheduled, true)
		doubleClickEventScheduled = nil
	end
end
function getTempHP()
	local maxHP = getTempStat(characters[id].HP.max,'maxHP',1)
	local currentHP = getTempStat(characters[id].HP.current, 'currentHP',1)
	if(maxHP == "-" and currentHP == "-") then
		--nothing changed.
		return "-"
	end
	if(maxHP == "-") then
		--only current HP changed.
		maxHP = characters[id].HP.max
	end
	if(currentHP == "-") then
		--only max HP changed.
		currentHP = characters[id].HP.current
	end
	
	return currentHP .. '/' .. maxHP
end
function shouldGreyOutInventory()
	return characters[id].HP.current <= 0 or inventoryScreen:IsSpriteOrderable() == false
end
function getInventoryTHAC0()
	local str = characters[id].THAC0.current
	if(characters[id].THAC0.offhand) then
		str = str .. "\n" .. characters[id].THAC0.offhand
	end
	return str
end
function getInventoryDamage()
	local str = characters[id].damage.min .. ' - ' .. characters[id].damage.max
	if(characters[id].damage.minOffhand and characters[id].damage.maxOffhand) then
		str = str .. "\n" .. characters[id].damage.minOffhand .. ' - ' .. characters[id].damage.maxOffhand 
	end
	return str
end
function getInventoryDamageDetails()
	if characters[id].damage.detailsOffhand == nil or characters[id].damage.detailsOffhand == "" then
		return characters[id].damage.details
	else
		return characters[id].damage.details.."\n\n"..characters[id].damage.detailsOffhand
	end
end
function getInventoryTHAC0Details()
	if characters[id].THAC0.detailsOffhand == nil or characters[id].THAC0.detailsOffhand == "" then
		return characters[id].THAC0.details
	else
		return characters[id].THAC0.details.."\n\n"..characters[id].THAC0.detailsOffhand
	end
end
function scrollGroundItems()
	forceGroundItemsScrollbar = true
	if scrollDirection > 0 then
		Infinity_OnGroundPage(-1)
	elseif scrollDirection < 0 then
		Infinity_OnGroundPage(1)
	end
	currentFakePage = Infinity_GetCurrentGroundPage()
end

fakeItemList = {}
currentFakePage = 1
currentMaxFakePages = 1
forceGroundItemsScrollbar = false

function scrollGroundItemsFunction(top, height, contentHeight)
	if forceGroundItemsScrollbar then
		forceGroundItemsScrollbar = false
		return (currentFakePage / currentMaxFakePages) * (height - contentHeight)
	elseif top ~= 0 and height ~= contentHeight and currentMaxFakePages ~= 0 then
		local currentPage = currentFakePage
		currentFakePage = math.floor((top / (height - contentHeight) * currentMaxFakePages))
		if currentPage > currentFakePage then
			Infinity_OnGroundPage(-1)
		elseif currentPage < currentFakePage then
			Infinity_OnGroundPage(1)
		end
		return nil
	end
end

function isGroundScrollbarEnabled()
	local maxPages = Infinity_GetMaxGroundPage()
	if currentMaxFakePages ~= maxPages then
		currentMaxFakePages = maxPages

		fakeItemList = {}
		for i = 1, currentMaxFakePages+1 do
			fakeItemList[i] = 1
		end
	end

	return currentMaxFakePages > 0
end
`
menu
{
	name 'INVENTORY'
	align center center
	ignoreEsc
	
	onOpen 
	"
		Infinity_ActivateInventory()
		pushSidebars()
		doubleClickEventScheduled = nil

		for i = 1, Infinity_GetMaxGroundPage()+1 do
			fakeItemList[i] = 1
		end
		currentFakePage = Infinity_GetCurrentGroundPage()
		currentMaxFakePages = Infinity_GetMaxGroundPage()
	"
	onClose 
	"
		Infinity_PopMenu('CHARACTER_COLOR')
		Infinity_PopMenu('ITEM_DESCRIPTION')
		Infinity_PopMenu('ITEM_IDENTIFY')
		popSidebars()

		fakeItemList = {}
	"
	label
	{
		area 0 0 864 710
		mosaic INVENTOR 
	}
	
	label
	{
		area		524 50 330 37
		text lua	"getStatsTitle()"
		text style	"label"
		text color 'D'
	}
	label
	{
		enabled		"tempStats[id] ~= nil"
		area		678 87 78 23
		text		"CURRENT_LABEL"
		text style	"label"
		text color 'D'
		text point 10
	}
	label
	{
		enabled		"tempStats[id] ~= nil"
		area		762 87 80 23
		text		"NEW_LABEL"
		text style	"label"
		text color 'D'
		text point 10
	}
	text
	{
		area		528 120 140 62
		text		"ARMOR_CLASS_LABEL"
		text style	"label"
		enabled		"tempStats[id] ~= nil"
		tooltip lua "characters[id].AC.details"
		text align left center
	}
	label
	{
		area		678 120 74 62
		text lua	"getStat(characters[id].AC.current,'AC',-1)"
		text style	"label"
		align center center
	}
	label
	{
		enabled		"tempStats[id] ~= nil"
		area		762 118 76 64
		text lua	"getTempStat(characters[id].AC.current,'AC',-1)"
		text style	"label"
		align center center
	}
	
	text
	{
		area		528 194 140 64
		text		"HIT_POINTS_LABEL"
		text style	"label"
		enabled		"tempStats[id] ~= nil"
		tooltip lua "characters[id].HP.details"
		text align left center
	}
	label
	{
		area		678 194 74 64
		text lua	"characters[id].HP.current .. '/' .. getStat(characters[id].HP.max, 'HP', 1) "
		text style	"label"
		align center center
	}
	label
	{
		enabled		"tempStats[id] ~= nil"
		area		762 194 76 68
		text lua	"getTempHP()"
		text style	"label"
		align center center
	}
	
	text
	{
		area		528 276 140 60
		text		"THAC0_LABEL"
		text style	"label"
		enabled		"tempStats[id] ~= nil"
		tooltip lua "characters[id].THAC0.details"
		text align left center
	}	
	label
	{
		area		678 270 74 66
		text lua	"getStat(characters[id].THAC0.current,'THAC0', -1)"
		text style	"label"
		align center center
	}
	label
	{
		enabled		"tempStats[id] ~= nil"
		area		766 270 76 66
		text lua	"getTempStat(characters[id].THAC0.current,'THAC0',-1)"
		text style	"label"
		align center center
	}
	
	text
	{
		area		528 354 140 52
		text		"DAMAGE_LABEL"
		text style	"label"
		enabled		"tempStats[id] ~= nil"
		tooltip lua "characters[id].damage.details"
		text align left center
	}	
	label
	{
		area		678 347 78 59
		text lua	"getStat(characters[id].damage.min,'dmgMin',1) .. ' - ' .. getStat(characters[id].damage.max, 'dmgMax', 1)"
		text style	"label"
		align center center
	}
	label
	{
		enabled		"tempStats[id] ~= nil"
		area		762 347 80 59
		text lua	"getTempDamage()"
		text style	"label"
		align center center
	}
	
	--stat details begin
	label
	{
		enabled		"tempStats[id] == nil"
		area 512 44 349 376
		mosaic "INVSTATS"
	}
	label
	{
		enabled		"tempStats[id] == nil"
		area		540 70 38 40
		text lua	"characters[id].AC.current"
		text style	"label"
		align center center
	}
	text
	{
		enabled		"tempStats[id] == nil"
		area 605 55 248 79
		text lua "characters[id].AC.details"
		text style "normal"
		scrollbar 'GUISCRC'
	}
	label
	{
		enabled		"tempStats[id] == nil"
		area		534 159 44 42
		text lua	"characters[id].HP.current .. '/' .. characters[id].HP.max"
		text style	"label"
		align center center
	}
	text
	{
		enabled		"tempStats[id] == nil"
		area 605 150 248 76
		text lua "characters[id].HP.details"
		text style "normal"
		scrollbar 'GUISCRC'
	}
	
	label
	{
		enabled		"tempStats[id] == nil"
		area		540 254 34 42
		text lua	"getInventoryTHAC0()"
		text style	"label"
		align center center
	}
	text
	{
		enabled		"tempStats[id] == nil"
		area 605 244 248 72
		text lua "getInventoryTHAC0Details()"
		text style "normal"
		scrollbar 'GUISCRC'
	}
	
	label
	{
		enabled		"tempStats[id] == nil"
		area		536 348 42 39
		text lua	"getInventoryDamage()"
		text style	"label"
		align center center
	}
	text
	{
		enabled		"tempStats[id] == nil"
		area 605 332 248 74
		text lua "getInventoryDamageDetails()"
		text style "normal"
		scrollbar 'GUISCRC'
	}
	
	--stat details end
	
	button
	{
		area 299 177 128 160
		paperdoll 1
		actiondrag "Infinity_SwapWithAppearance()"
	}
	
	button
	{
		area 13 570 68 100
		encumbrance
	}
	
	label
	{
		area 108 55 186 32
		text lua "characters[id].name"
		text style "label"
	}
	label
	{
		area 82 6 700 44
		text "INVENTORY_TITLE"
		text style "title"
	}
	label
	{
		area 29 201 200 30
		text "QUICK_WEAPONS_LABEL"
		text style "label"
	}
	label
	{
		area 29 306 162 30
		text "QUICK_ITEMS_LABEL"
		text style "label"
	}
	label
	{
		area 83 98 150 28
		text "QUIVER_LABEL"
		text style "label"
	}
	label
	{
		area 695 437 83 24
		text "GROUND_LABEL"
		text style "label"
		align left center
	}
	label
	{
		area 778 437 75 24
		text lua "Infinity_GetCurrentGroundPage()+1 .. '/' .. Infinity_GetMaxGroundPage()+1"
		text style "label"
		align right center
	}
	label
	{
		area 390 490 118 23
		text lua "characters[id].gold"
		text style "label"
	}
	label
	{
		area 302 55 210 32
		text lua "characters[id].class"
		text style "label"
	}
	text
	{
		area 18 448 340 52
		text lua "TEXT_inventoryError"
		scrollbar 'GUISCRC'
		text style normal
	}


	slot {name "slot_inv_1"		area 26 243 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.weapon0"		}
	slot {name "slot_inv_2"		area 78 243 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.weapon1"		}
	slot {name "slot_inv_3"		area 130 243 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.weapon2"		}
	slot {name "slot_inv_4"		area 182 243 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.weapon3"		}
	
	slot {name "slot_inv_5"		area 26 347 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.personal0"	}
	slot {name "slot_inv_6"		area 78 347 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.personal1"	}
	slot {name "slot_inv_7"		area 130 347 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.personal2"	}
	
	slot {name "slot_inv_11"		area 242 98 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.armor"		}
	slot {name "slot_inv_12"		area 294 98 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.gauntlets"	}
	slot {name "slot_inv_13"		area 346 98 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.helmet"		}
	slot {name "slot_inv_14"		area 398 98 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.amulet"		}
	slot {name "slot_inv_15"		area 78 138 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.quiver0"		}
	slot {name "slot_inv_16"		area 130 138 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.quiver1"		}
	slot {name "slot_inv_17"		area 182 138 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.quiver2"		}
	slot {name "slot_inv_21"		area 393 361 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.belt"		}
	slot {name "slot_inv_22"		area 218 302 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ringleft"	}
	slot {name "slot_inv_23"		area 462 302 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ringright"	}
	slot {name "slot_inv_24"		area 282 361 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.cloak"		}
	slot {name "slot_inv_25"		area 338 361 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.boots"		}
	slot {name "slot_inv_26"		area 461 244 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.shield"		}
	
	slot {name "slot_inv_30"		area 87 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group0"		}
	slot {name "slot_inv_31"		area 87 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group1"		}
	slot {name "slot_inv_32"		area 140 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group2"		}
	slot {name "slot_inv_33"		area 140 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group3"		}
	slot {name "slot_inv_34"		area 193 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group4"		}
	slot {name "slot_inv_35"		area 193 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group5"		}
	slot {name "slot_inv_36"		area 246 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group6"		}
	slot {name "slot_inv_37"		area 246 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group7"		}
	slot {name "slot_inv_38"		area 299 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group8"		}
	slot {name "slot_inv_39"		area 299 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group9"		}
	slot {name "slot_inv_40"		area 352 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group10"		}
	slot {name "slot_inv_41"		area 352 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group11"		}
	slot {name "slot_inv_42"		area 405 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group12"		}
	slot {name "slot_inv_43"		area 405 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group13"		}
	slot {name "slot_inv_44"		area 458 571 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group14"		}
	slot {name "slot_inv_45"		area 458 626 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.group15"		}

	list
	{
		column 
		{ 
			width	100
			label
			{
				area 		0,0,928,-1
			}
		}
		
		area 710 478 136 220
		rowheight	220
		hidehighlight
		table		"fakeItemList"
		var			currentFakePage
		scrollbar	'GUISCRC'
		scrollbar func "scrollGroundItemsFunction"
		scrollbar respectConstraints
		actionScroll "scrollGroundItems()"
		enabled "isGroundScrollbarEnabled()"
	}
 
	slot {name "slot_inv_68"		area 710 478 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground0"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_69"		area 766 478 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground1"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_70"		area 710 534 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground2"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_71"		area 766 534 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground3"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_72"		area 710 590 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground4"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_73"		area 766 590 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground5"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_74"		area 710 646 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground6"	actionScroll "scrollGroundItems()"	}
	slot {name "slot_inv_75"		area 766 646 52 52	bam "STONSLOT"	slotinfo "characters[id].equipment.ground7"	actionScroll "scrollGroundItems()"	}

	button
	{
		area 458 98 50 52
		bam INVBUT
		colordisplay 1
		action
		"
			Infinity_PushMenu('CHARACTER_COLOR', 0, 0)
		"
	}
	label --this has to be last so it draws over top of everything.
	{
		area 0 0 864 710
		enabled "shouldGreyOutInventory()"
		rectangle 0
		rectangle opacity 200
	}
}
`
SLIDER_color_hair_start = 1
SLIDER_color_skin_start = 1
SLIDER_color_major_start = 1
SLIDER_color_minor_start = 1

SLIDER_color_hair = 1
SLIDER_color_skin = 1
SLIDER_color_major = 1
SLIDER_color_minor = 1
`
menu
{
	name 'CHARACTER_COLOR'
	align center center
	ignoreesc
	
	onOpen
	"
		Infinity_UpdateLuaStats()
		
		SLIDER_color_hair = characters[id].colors.hair
		SLIDER_color_skin = characters[id].colors.skin
		SLIDER_color_major = characters[id].colors.major
		SLIDER_color_minor = characters[id].colors.minor
		
		SLIDER_color_hair_start = SLIDER_color_hair
		SLIDER_color_skin_start = SLIDER_color_skin
		SLIDER_color_major_start = SLIDER_color_major
		SLIDER_color_minor_start = SLIDER_color_minor
	"
	onClose
	"
		if(SLIDER_color_hair_start ~= -1) then Infinity_SetHairColor(SLIDER_color_hair_start) end
		if(SLIDER_color_skin_start ~= -1) then Infinity_SetSkinColor(SLIDER_color_skin_start) end
		if(SLIDER_color_major_start ~= -1) then Infinity_SetMajorColor(SLIDER_color_major_start) end
		if(SLIDER_color_minor_start ~= -1) then Infinity_SetMinorColor(SLIDER_color_minor_start) end
	"
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 158 1024 609
		mosaic GUIHSB
	}
	label
	{
		area 24 162 414 44
		text "COLOR_CHOICES_TITLE"
		text style "title"
	}
	
	button
	{
		area 488 276 114 160
		align center center
		paperdoll 0
	}
	button
	{
		area 598 276 114 160
		align center center
		paperdoll 1
	}
	
	label
	{
		enabled "characters[id].PC == 1"
		area 378 298 42 44
		colordisplay 6
	}
	label
	{
		enabled "characters[id].PC == 1"
		area 378 356 42 44
		colordisplay 3
	}
	label
	{
		area 378 478 42 44
		colordisplay 2
	}
	label
	{
		area 378 534 42 44
		colordisplay 1
	}
	
	label
	{
		area 56 240 382 30
		text "APPEARANCE_LABEL"
		text style "label"
		text point 14
		text align left center
	}
	
	label
	{
		enabled "characters[id].PC == 1"
		area 304 298 74 44
		text "HAIR_LABEL"
		text style "label"
	}
	slider
	{
		palette 6
		enabled "characters[id].PC == 1"
		area 46 298 258 44
		bam	 'SLDRSTAR'
		scaleToClip
		position "SLIDER_color_hair"
		sequence 0
		frame	 1
		settings lua "game:GetPaletteSize(6)"
		action
		"
			Infinity_SetHairColor(SLIDER_color_hair)
		"
	}

	label
	{
		enabled "characters[id].PC == 1"
		area 304 356 74 44
		text "SKIN_LABEL"
		text style "label"
	}
	slider
	{
		palette 3
		enabled "characters[id].PC == 1"
		area 46 356 258 44
		bam	 'SLDRSTAR'
		scaleToClip
		position "SLIDER_color_skin"
		sequence 0
		frame	 1
		settings lua "game:GetPaletteSize(3)"
		action
		"
			Infinity_SetSkinColor(SLIDER_color_skin)
		"
	}
	
	label
	{
		area 56 428 382 30
		text "CLOTHING_LABEL"
		text style "label"
		text point 14
		text align left center
	}
	
	label
	{
		area 304 478 74 44
		text "MAJOR_LABEL"
		text style "label"
	}
	slider
	{
		palette 2
		area 46 478 258 44
		bam	 'SLDRSTAR'
		scaleToClip
		position "SLIDER_color_major"
		sequence 0
		frame	 1
		settings lua "game:GetPaletteSize(2)"
		action
		"
			Infinity_SetMajorColor(SLIDER_color_major)
		"
	}
	
	label
	{
		area 304 534 74 44
		text "MINOR_LABEL"
		align center center
		text style "label"
	}
	slider
	{
		palette 1
		area 46 534 258 44
		bam	 'SLDRSTAR'
		scaleToClip
		position "SLIDER_color_minor"
		sequence 0
		frame	 1
		settings lua "game:GetPaletteSize(1)"
		action
		"
			Infinity_SetMinorColor(SLIDER_color_minor)
		"
	}
	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		sequence 2
		text "CANCEL_BUTTON"
		text style "button"
		action
		"
			Infinity_PopMenu('CHARACTER_COLOR',0,0)
		"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		sequence 2
		text "DONE_BUTTON"
		text style "button"
		action
		"
			--save settings
			SLIDER_color_hair_start = SLIDER_color_hair
			SLIDER_color_skin_start = SLIDER_color_skin
			SLIDER_color_major_start = SLIDER_color_major
			SLIDER_color_minor_start = SLIDER_color_minor
			
			if (e:GetActiveEngine() == createCharScreen) then
				createCharScreen:OnDoneButtonClick()
			end
			
			Infinity_PopMenu('CHARACTER_COLOR',0,0)
		"
	}
}

menu
{
	name 'WORLD_LEVEL_UP_BUTTONS'
	align right top
	offset -65 0
	ignoreesc
	enabled "0" --disable this menu for now.
	button
	{
		enabled "Infinity_CanLevelUp(0)"
		bam GUIOSW
		area 0 14 44 44
		sequence 0
		action "Infinity_ActivateRecord(0)"
		pulse 1
	}
	button
	{
		enabled "Infinity_CanLevelUp(1)"
		bam GUIOSW
		area 0 106 44 44
		sequence 0
		action "Infinity_ActivateRecord(1)"
		pulse 1
	}
	button
	{
		enabled "Infinity_CanLevelUp(2)"
		bam GUIOSW
		area 0 198 44 44
		sequence 0
		action "Infinity_ActivateRecord(2)"
		pulse 1
	}
	button
	{
		enabled "Infinity_CanLevelUp(3)"
		bam GUIOSW
		area 0 290 44 44
		sequence 0
		action "Infinity_ActivateRecord(3)"
		pulse 1
	}
	button
	{
		enabled "Infinity_CanLevelUp(4)"
		bam GUIOSW
		area 0 382 44 44
		sequence 0
		action "Infinity_ActivateRecord(4)"
		pulse 1
	}
	button
	{
		enabled "Infinity_CanLevelUp(5)"
		bam GUIOSW
		area 0 474 44 44
		sequence 0
		action "Infinity_ActivateRecord(5)"
		pulse 1
	}
	
}
menu
{
	name 'textflash'
	opacity lua 'getOpacityForInfoBlock(1000)'
	enabled 'getOpacityForInfoBlock(1000) ~= 0'
	align center top
	offset 0 10

	label
	{
		area 0 0 500 140	
		rectangle 4
		rectangle opacity 200 
	}
	label
	{
		area 92 10 348 26
		text lua "getTitleString()"
		text style "label"
		text align left center
		text point 14
		text color C
	}
	text
	{
		area 92 36 348 26
		text lua "getSubtitleString()"
		text style "label"
		text align left center
		text point 14
		text color D
		scrollbar 'GUISCRC'
		scrollbar hide lua "1"
	}

	text
	{
		area 20 64 472 62
		text lua "getBodyString()"
		text style "normal"
		text align left top
		scrollbar 'GUISCRC'
		scrollbar hide lua "1"
	}
	label
	{
		area 16 9 72 55
		bam 'GUILS10'
		sequence 2
		frame 0
	}
	button
	{
		area 0 0 500 140
		action
		"
			if(sidebarsGreyed ~= 1) then
				e:GetActiveEngine():OnLeftPanelButtonClick(2)
				local tf = next(textflashes)
				setSelectedQuest(textflashes[tf][5])
			end
		"
	}
	button
	{
		bam GUIOSW
		on esc
		area 448 4 44 44
		sequence 2
		action 
		"
			--end the animation
			local tf = next(textflashes)
			textflashes[tf] = nil
		"
	}
}


`
luaEdit = ""
luaEditDebugDump = 0
luaEditHistory = {}
luaEditMaxHistory = 10
luaEditHistoryIndex = 0
luaEditShowHistoryList = 0
luaEditHistoryListSelected = 0
function updateLuaHistory()
	local i = 2
	local tempTab = {}
	tempTab[1] = luaEdit
	while ( i <= luaEditMaxHistory ) do
		tempTab[i] = luaEditHistory[i-1]
		i = i + 1
	end
	luaEditHistory = tempTab
end
function loadLuaHistory()
	local i = 1
	while (i <= luaEditMaxHistory ) do
		luaEditHistory[i] = Infinity_GetINIString("Lua Edit","String"..i-1, "")
		i = i + 1
	end
end
function saveLuaHistory()
	local i = 1
	while (i <= luaEditMaxHistory ) do
		Infinity_SetINIValue("Lua Edit","String"..i-1, luaEditHistory[i])
		i = i + 1
	end
end
function luaEditHistoryUp()
	if(luaEditHistoryIndex <= 1) then return end
	luaEditHistoryIndex = luaEditHistoryIndex - 1
	luaEdit = luaEditHistory[luaEditHistoryIndex]
end
function luaEditHistoryDown()
	if(luaEditHistoryIndex == luaEditMaxHistory) then return end
	if(luaEditHistory[luaEditHistoryIndex + 1] == "") then return end
	luaEditHistoryIndex = luaEditHistoryIndex + 1
	luaEdit = luaEditHistory[luaEditHistoryIndex]
end

cheatGoldAmt = 1000000
cheatXpAmt = 500000

`
menu
{
	name 'cheatMenu'
	ignoreEsc	
        
        onOpen
	"
		if game:GetMissionPackInfo() then
			cheatAreaDisplayList = cheatAreasTutorial
		elseif game:GetMissionPackInfoTBP() then
			cheatAreaDisplayList = cheatAreasArena
		elseif game:GetMissionPackInfo25() then
			cheatAreaDisplayList = cheatAreasExpansion
		else
			cheatAreaDisplayList = cheatAreas
		end
	"

	label
	{
		area 100 0 809 298
		mosaic 'GUWBTP30'	
	}
	list
	{
		column 
		{
			width 20 
			label
			{
				area 0 0 -1 -1
				text lua "cheatAreaDisplayList[rowNumber][1]"
				text style "list"
			}
		}
		column 
		{ 
			width 80 
			label
			{
				area 0 0 -1 -1
				text lua "cheatAreaDisplayList[rowNumber][2]"
				text style "list"
			}
		}

		area 122 6 492 240
		
		rowheight	18
		table		"cheatAreaDisplayList"
		var		cheatTeleportArea
		scrollbar	'GUISCRC'
	}
	button
	{
		area		122 246 140 42
		bam			GUIOSTSM
		sequence	6
		text		"TRAVEL_BUTTON"
		text style	"button"
		action 		"C:MoveToArea(cheatAreaDisplayList[cheatTeleportArea][1])"
	}
	button
	{
		area		620 162 140 42
		bam			GUIOSTSM
		sequence	6
		text			"GODBOW_LABEL"
		text style	"button"
		action		"C:CreateItem('godbow')"
	}
	button
	{
		area		620 204 140 42
		bam			GUIOSTSM
		sequence	6
		text			"GIVE_GOLD_LABEL"
		text style	"button"
		action		"C:AddGold(cheatGoldAmt)"
	}
	edit
	{
		area		766 204 138 42
		var		cheatGoldAmt
		text style	"edit"
		maxlines	1
	}

	button
	{
		area		620 246 140 42
		bam			GUIOSTSM
		sequence	6
		text			"GIVE_XP_LABEL"
		text style	"button"
		action		"C:SetCurrentXP(cheatXpAmt)"
	}
	edit
	{
		area		766 246 138 42
		var		cheatXpAmt
		text style	"edit"
		maxlines	1
	}

	button
	{
		area		766 162 140 42
		bam			GUIOSTSM
		sequence	6
		text			"EXPLORE_LABEL"
		text style	"button"
		action		"C:ExploreArea()"
	}

}
menu
{
	name "luaHistoryMenu"
	offset 500 -32
	align right bottom
	label
	{
		area 0 0 809 300
		mosaic 'GUWBTP30'
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "luaEditHistory[rowNumber]"
				text style	"list"
			}
		}
		area 20 10 400 298
		rowheight	24
		var luaEditHistoryListSelected
		table		"luaEditHistory"
		scrollbar	'GUISCRC'
		action
		"
			luaEdit = luaEditHistory[luaEditHistoryListSelected]
		"
	}
}
menu
{
	name 'cheatConsole'
	align center bottom
	ignoreEsc

	onOpen 
	"
		toolbarTop = 50
		Infinity_PushMenu('WORLD_MESSAGES')
		Infinity_PushMenu('cheatMenu', 0, 0);
		Infinity_FocusTextEdit('luaEditArea'); 
		luaEdit = trim(luaEdit)
		loadLuaHistory()
	"
	onClose 
	"
		Infinity_PopMenu('cheatMenu', 0, 0);
		Infinity_PopMenu('luaHistoryMenu', 0, 0);
	"
	label
	{
		area 0 0 809 50
		mosaic GUWBTP20
	}
	edit
	{
		name				"luaEditArea"
		area				12 8 790 24
		var					luaEdit
		scrollbar			'GUISCRC'
		text style			"edit"
		fill            	112 111 111 64
		text useFontZoom	0
		action
		"
			--if key_pressed is return
			if (key_pressed == 13) then
				updateLuaHistory()
				saveLuaHistory()
				Infinity_LuaConsoleInput(luaEditObjectId,luaEditDebugDump)
				return -1
			end
			if (key_pressed == 27) then
				return 0
			end
			return 1
		"
	}
	button
	{
		area		816 6 32 32
		bam			ROUNDBUT
		toggle		luaEditShowHistoryList
		action
		"
			if(luaEditShowHistoryList == 0) then
				Infinity_PopMenu('luaHistoryMenu',0,0)
			else
				Infinity_PushMenu('luaHistoryMenu',0,0)
			end
		"
	}
	button
	{
		enabled "Infinity_TextEditHasFocus()"
		on up
		action
		"
			luaEditHistoryUp()
		"
	}
	button
	{
		enabled "Infinity_TextEditHasFocus()"
		on down
		action
		"
			luaEditHistoryDown()
		"
	}

}
`
cloudLoadState=0
function CheckCloudSaveStatus()
	Infinity_UpdateCloudSaveState()
	if(cloudLoadState == 0) then
		Infinity_PopMenu()
	end
	return GetCloudLoadingText()
end
function GetCloudLoadingText()
	if(cloudLoadState == 1 or cloudLoadState == 0) then
		return t('DOWNLOADING_SAVE_NORMAL')
	end
	if(cloudLoadState == 2) then
		return t('SEARCHING_SAVE_NORMAL')
	end
	return t('CLOUD_STATE_UNDEFINED_NORMAL')
end
`
menu
{
	name 'CloudSaveUpdateMenu'
	modal
	label
	{
		area 0 0 408 418
		mosaic GUIERR
	}
	label 
	{
		area 82 74 242 88
		text lua "CheckCloudSaveStatus()"
		text style "label"
	}
	button
	{
		area 		102 318 200 44
		bam 		GUIOSTUM
		sequence	0
		text		"SKIP_BUTTON"
		text style	"button"
		on 			escape
		action
		"
			Infinity_PopMenu()
		"	
	}
}
`
messageBoxCurMessage = nil
messageBoxMessages = {}
function initMessageBox(message)
	messageBoxMessages[message] = 1
	if(messageBoxCurMessage ~= nil) then
		--message box already active
		return
	end
	getNextMessage()
	Infinity_PushMenu('LuaMessageBox',0,0)
end

function getNextMessage()
	i = 1
	while ( i <= messageBoxMessageCount ) do
		showMessage = messageBoxMessages[i]
		if ( showMessage ~= nil ) then
			messageBoxCurMessage = i
			return 1
		end
		i = i + 1
	end
	--whole table scanned, all messages have been displayed
	return 0
end
`
menu
{
	name 'LuaMessageBox'
	align center center
	ignoreesc
	modal
	label
	{
		area 0 0 657 234
		mosaic GUIERR6
	}
	label
	{
		area 29 21 580 126
		text lua "messages[messageBoxCurMessage]"
		text style	"label"
	}
	button
	{
		area 213 170 230 44
		bam GUIBUTNT
		text "DONE_BUTTON"
		text style	"button"
		action
		"
			messageBoxMessages[messageBoxCurMessage] = nil
			if(getNextMessage() == 0) then
				messageBoxCurMessage = nil
				Infinity_PopMenu()
			end
		"	
	}
}

`
	partyImport = {}
`
menu
{
	name 'IMPORTPARTY'
	align center center
	label 
	{
		mosaic 'GMPCARBD'
		area 0 0 1024 768
	}
	label
	{
		area 162 16 700 44
		text "CREATE_PARTY_TITLE"
		text style "title"
	}
	label
	{
		enabled		"game:GetMissionPackInfoTBP()"
		area 		54 584 902 62
		scrollbar	'GUISCRC'
		text style	"normal"
		text 			69563
	}

	--portraits
	label
	{
		area 67 180 64 90
		bam 'GUIRSP10'
		sequence 0
	}
	button
	{
		area 71 182 56 86
		bitmap lua "partyImport.character[1].portrait"
		clickable lua "partyImport.character[1].name ~= ''"
		action
		"
			createPartyScreen:OnPortraitButtonClick(0)
		"
	}
	label
	{
		area 67 315 64 90
		bam 'GUIRSP10'
		sequence 0
	}
	button
	{
		area 71 317 56 86
		bitmap lua "partyImport.character[2].portrait"
		clickable lua "partyImport.character[2].name ~= ''"
		action
		"
			createPartyScreen:OnPortraitButtonClick(1)
		"
	}
	label
	{
		area 67 454 64 90
		bam 'GUIRSP10'
		sequence 0
	}
	button
	{
		area 71 456 56 86
		bitmap lua "partyImport.character[3].portrait"
		clickable lua "partyImport.character[3].name ~= ''"
		action
		"
			createPartyScreen:OnPortraitButtonClick(2)
		"
	}
	label
	{
		area 557 180 64 90
		bam 'GUIRSP10'
		sequence 0
	}
	button
	{
		area 561 182 56 86
		bitmap lua "partyImport.character[4].portrait"
		clickable lua "partyImport.character[4].name ~= ''"
		action
		"
			createPartyScreen:OnPortraitButtonClick(3)
		"
	}
	label
	{
		area 557 315 64 90
		bam 'GUIRSP10'
		sequence 0
	}
	button
	{
		area 561 317 56 86
		bitmap lua "partyImport.character[5].portrait"
		clickable lua "partyImport.character[5].name ~= ''"
		action
		"
			createPartyScreen:OnPortraitButtonClick(4)
		"
	}
	label
	{
		area 557 454 64 90
		bam 'GUIRSP10'
		sequence 0
	}
	button
	{
		area 561 456 56 86
		bitmap lua "partyImport.character[6].portrait"
		clickable lua "partyImport.character[6].name ~= ''"
		action
		"
			createPartyScreen:OnPortraitButtonClick(5)
		"
	}

	button
	{
		area 528 720 204 44
		bam 'GUIOSTUM'
		sequence 1
		text "PLAY_IMPORT_BUTTON" -- Play
		text style 'button'
		clickable lua "partyImport.playbuttonclickable"
		action 
		"
			createPartyScreen:OnDoneButtonClick()
		"
	}
	button
	{
		on escape
		area 306 720 204 44
		bam 'GUIOSTUM'
		sequence 0
		text "BACK_BUTTON" -- Back
		text style 'button'
		action 
		"
			createPartyScreen:OnBackButtonClick()
		"
	}

	--delete/create buttons
	button
	{
		area 155 180 300 44
		bam 'GUIOSTCL'
		sequence 0
		text lua "partyImport.character[1].createdelete"
		text style "button"
		action
		"
			createPartyScreen:OnCreateDeleteButtonClick(0)
		"
	}
	button
	{
		area 155 317 300 44
		bam 'GUIOSTCL'
		sequence 2
		text lua "partyImport.character[2].createdelete"
		text style "button"
		action
		"
			createPartyScreen:OnCreateDeleteButtonClick(1)
		"
	}
	button
	{
		area 155 452 300 44
		bam 'GUIOSTCL'
		sequence 1
		text lua "partyImport.character[3].createdelete"
		text style "button"
		action
		"
			createPartyScreen:OnCreateDeleteButtonClick(2)
		"
	}
	button
	{
		area 645 180 300 44
		bam 'GUIOSTCL'
		sequence 0
		text lua "partyImport.character[4].createdelete"
		text style "button"
		action
		"
			createPartyScreen:OnCreateDeleteButtonClick(3)
		"
	}
	button
	{
		area 645 317 300 44
		bam 'GUIOSTCL'
		sequence 2
		text lua "partyImport.character[5].createdelete"
		text style "button"
		action
		"
			createPartyScreen:OnCreateDeleteButtonClick(4)
		"
	}
	button
	{
		area 645 452 300 44
		bam 'GUIOSTCL'
		sequence 1
		text lua "partyImport.character[6].createdelete"
		text style "button"
		action
		"
			createPartyScreen:OnCreateDeleteButtonClick(5)
		"
	}

	-- character labels
	label
	{
		area 155 228 314 50
		text lua "partyImport.character[1].name"
		text style "title"
	}
	label
	{
		area 155 365 314 50
		text lua "partyImport.character[2].name"
		text style "title"
	}
	label
	{
		area 155 500 314 50
		text lua "partyImport.character[3].name"
		text style "title"
	}
	label
	{
		area 645 228 314 50
		text lua "partyImport.character[4].name"
		text style "title"
	}
	label
	{
		area 645 365 314 50
		text lua "partyImport.character[5].name"
		text style "title"
	}
	label
	{
		area 645 500 314 50
		text lua "partyImport.character[6].name"
		text style "title"
	}
}

`
	highlightBG = false
	highlightSOD = false
	highlightBP = false
	logoFrame = 0

	function startThreeBookHighlight(book)
		if book == 1 and highlightBG == true then
			return 1
		elseif book == 2 and highlightSOD == true then
			return 1
		elseif book == 3 and highlightBP == true then
			return 1
		else
			return 0
		end
	end
`
menu
{
	name 'START'
	align center center
	ignoreesc
	onOpen "
		e:CheckGUISong()
		local state = startEngine:GetEngineState()
		if lastStartMenu and lastStartMenu ~= 'START' then
			Infinity_PushMenu(lastStartMenu)
			lastStartMenu = nil
		elseif state == 1 then
			Infinity_PushMenu('START_SP')
		elseif state == 2 then
			Infinity_PushMenu('START_MP')
		elseif state == 0 then
			Infinity_PushMenu('START_MAIN')
		end
		Infinity_SetBackground('BACKGROUND')
	"
	onClose "
		local state = startEngine:GetEngineState()
		if state == 1 then
			Infinity_PopMenu('START_SP')
		elseif state == 2 then
			Infinity_PopMenu('START_MP')
		elseif state == 0 or state == 3 then
			Infinity_PopMenu('START_MAIN')
		end

	"

	label
	{
		area 6 0 1024 768
		mosaic 'START3EE'
	}

	text --soa
	{
		bam 'LOGOSOA'
		sequence 0
		frame lua "startThreeBookHighlight(1)"
		area 106 270 202 240
		align center center
		action 
		"
			logoFrame = 0
			startEngine:OnSoAButtonClick(true)
			Infinity_PushMenu('START_MAIN')
		"
		actionEnter
		"
			highlightBG = true
		"
		actionExit
		"
			highlightBG = false
		"
	}
	text --tob
	{
		bam 'LOGOTOB'
		sequence 0
		frame lua "startThreeBookHighlight(2)"
		area 400 270 235 224
		align center center
		action 
		"
			logoFrame = 1
			startEngine:OnToBButtonClick(true)
			Infinity_PushMenu('START_MAIN')
		"
		actionEnter
		"
			highlightSOD = true
		"
		actionExit
		"
			highlightSOD = false
		"
	}
	text --black pits
	{
		bam 'LOGOTBP'
		sequence 0
		frame lua "startThreeBookHighlight(3)"
		area 718 282 226 212
		align center center
		action 
		"
			logoFrame = 2
			startEngine:OnTBPButtonClick(true)
			Infinity_PushMenu('START_MAIN')
		"
		actionEnter
		"
			highlightBP = true
		"
		actionExit
		"
			highlightBP = false
		"
	}

	button --credits
	{
		bam 'GUIOSTUL'
		sequence 0
		area 178 714 234 46
		pad 10 8 10 8
		text style "button"
		text "CREDITS_BUTTON"
		action 
		"
			Infinity_PushMenu('CREDITS')
		"
	}
	button --quit
	{
		bam 'GUIOSTUM'
		sequence 0
		area 416 714 206 44
		pad 10 8 10 8
		text style "button"
		text "QUIT_GAME_BUTTON"
		enabled "not e:IsTouchUI()"
		action 
		"
			startEngine:OnQuitButtonClick()
		"
	}
	button --options
	{
		bam 'GUIOSTUR'
		sequence 0
		area 628 714 234 42
		pad 10 8 10 8
		text style "button"
		text "OPTIONS_BUTTON"
		action 
		"
			Infinity_TransitionMenu('START_OPTIONS')
			optionsScreen:SetEngineState(1)
			startEngine:OnOptionsButtonClick()
			lastStartMenu = 'START'
		"
	}
	
	label
	{
		area 448 606 134 44
		text lua "versionString"
		text style	"label"
		text point	10
		align center center
	} 
}

menu
{
	name 'START_MAIN'
	align center center
	ignoreEsc

	onOpen	"
		canContinue = startEngine:HasGameToContinue()
	"

	label
	{
		area 0 0 1024 768
		mosaic 'START'
	}
	label
	{
		area 112 26 786 202	
		bam 'TITLE'
		sequence 0
		align center center
		frame lua 'logoFrame'
	}
	label
	{
		area 338 192 352 456	
		bam 'BIGLOGO'
		align center center
		frame lua 'logoFrame'
	}


	button
	{
		bam 'GUIOSTCL'
		area 364 662 302 44
		pad 10 8 10 8
		text style "button"
		--text 9372
		text "CONTINUE_BUTTON"
		clickable lua "canContinue"
		action "startEngine:OnContinueGame()"
	}
	button
	{
		bam 'STARTMBT'
		sequence 0
		area 112 294 262 74
		pad 10 8 10 8
		text style "button"
		text "SINGLEPLAYER_BUTTON"
		--text 15413
		action 
		"
			startEngine:SetEngineState(1)
			Infinity_TransitionMenu('START_SP')
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 3
		area 649 300 266 74
		pad 10 8 10 8
		text style "button"
		text "MULTIPLAYER_BUTTON"
		action 
		"
			startEngine:OnMultiPlayerButtonClick()
		"
	}
	--button
	--{
	--	bam 'STARTMBT'
	--	sequence 1
	--	area 112 374 236 84
	--	pad 10 8 10 8
	--	text style "button"
	--	text "HOW_TO_PLAY_BUTTON"
	--	action 
	--	"
	--		Infinity_TransitionMenu('CONNECTION')
	--		startEngine:OnMultiPlayerButtonClick()
	--	"
	--}
	button
	{
		bam 'STARTMBT'
		sequence 4
		area 682 378 233 84
		pad 10 8 10 8
		text style "button"
		text lua "Infinity_FetchString(74269)"
		enabled "e:IsTouchUI()"
		action 
		"
			startEngine:OnDLCImageClick()
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 2
		area 116 462 262 76
		pad 10 8 10 8
		text style "button"
		text "OPTIONS_BUTTON"
		action "
			Infinity_TransitionMenu('START_OPTIONS')
			optionsScreen:SetEngineState(1)
			startEngine:OnOptionsButtonClick()
			lastStartMenu = 'START_MAIN'
		"
	}
	button
	{
		area 649 462 260 76
		bam 'STARTMBT'
		sequence 5
		pad 10 8 10 8
		text style "button"
		text "BACK_BUTTON"
		action 
		"
			e:GetObjectGame():SetCampaign('')
			Infinity_PopMenu()
			"
	}
}
menu
{
	name 'START_SP'
	align center center
	ignoreEsc

	label
	{
		area 0 0 1024 768
		mosaic 'START'
	}

	label
	{
		area 112 26 786 202	
		bam 'TITLE'
		sequence 0
		align center center
		frame lua 'logoFrame'
	}
	label
	{
		area 340 192 352 456	
		bam 'BIGLOGO'
		align center center
		frame lua 'logoFrame'
	}


	button
	{
		bam 'STARTMBT'
		sequence 0
		area 112 294 262 74
		pad 10 8 10 8
		text style "button"
		text "NEW_GAME_BUTTON"
		action 
		"
			Infinity_PopMenu(); 
			startEngine:OnNewGameButtonClick();
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 3
		area 649 300 266 74
		pad 10 8 10 8
		text style "button"
		text "LOAD_GAME_BUTTON"
		action "Infinity_PopMenu(); startEngine:OnLoadGameButtonClick()"
	}
	button
	{
		bam 'STARTMBT'
		sequence 1
		area 112 374 236 84
		pad 10 8 10 8
		text style "button"
		text "PREGENERATE_BUTTON"
		action "Infinity_PopMenu(); startEngine:OnPreGenerateButtonClick()"
	}
	button
	{
		bam 'STARTMBT'
		sequence 4
		area 682 378 233 84
		pad 10 8 10 8
		text style "button"
		text "IMPORT_GAME_BUTTON"
		action 
		"
			Infinity_PopMenu();
			startEngine:OnImportCharacterButtonClick();
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 2
		area 116 462 262 76
		pad 10 8 10 8
		text style "button"
		text "OPTIONS_BUTTON"
		action "
			Infinity_TransitionMenu('START_OPTIONS')
			optionsScreen:SetEngineState(1)
			startEngine:OnOptionsButtonClick()
			lastStartMenu = 'START_SP'
		"
	}
	button
	{
		area 649 462 260 76
		bam 'STARTMBT'
		sequence 5
		pad 10 8 10 8
		text style "button"
		text "BACK_BUTTON"
		action "startEngine:SetEngineState(0); Infinity_TransitionMenu('START')"
	}
}


`

function Redirect_magePageInfo()
	if bookMode == 0 then -- Regular
		if characters[id].hasSorcererBook then
			return t("SPELLS_CAN_CAST_LABEL") .. ": " .. characters[id].mageDetails[currentSpellLevel].slotsRemaining .. "/" .. characters[id].mageDetails[currentSpellLevel].maxMemorized
		else
			return t("MEMORIZED_LABEL") .. ": " .. #bottomSpells .. "/" .. characters[id].mageDetails[currentSpellLevel].maxMemorized
		end
	elseif bookMode == 1 then -- Sequencer/Contingency
		return t("SPELLS_LABEL") .. " :" .. #bottomSpells .. "/" .. #bottomSpellsPlaceHolder

	end
	return ""
end

contingencyDescription = 0

function mageBookDescription()
	if ((mageBookEnabled == true) or (bookMode == 1)) then
		if bookMode == 0 then
			if characters[id].mageSpells[currentSpellLevel][currentBookSpell] then
				return Infinity_FetchString(characters[id].mageSpells[currentSpellLevel][currentBookSpell].description)
			else
				return t('SPELL_MEMORIZATION_HELP')
			end
		elseif bookMode == 1 then
			if contingencyDescription == 0 and currentBookSpell ~= 0 then
				return Infinity_FetchString(bookSpells[currentBookSpell].description)
			else
				lastCurrentBookSpell = 0
				if contingencyDescription == 0 then
					contingencyDescription = mageBookStrings[contingencyResRef].tip
				end
				return Infinity_FetchString(contingencyDescription)
			end
		end
	end
	return ""
end
function mageBookTitle()
	if bookMode == 1 and mageBookStrings[contingencyResRef] then
		return t(mageBookStrings[contingencyResRef].title)
	else
		return t('MAGE_SPELLS_TITLE')
	end
end
function mageBookAction()
	if bookMode == 1 and mageBookStrings[contingencyResRef] then
		return t(mageBookStrings[contingencyResRef].action)
	else
		return t("MAGE_BOOK_LABEL")
	end
end


function makeBlankTable(num)
	local out = {}
	for i = 1,num do
		table.insert(out, {})
	end
	return out
end

function contingencyComplete()
	if showContingency then
		return #bottomSpells == #bottomSpellsPlaceHolder and (currentContingencyCondition or 0) > 0 and (currentContingencyTarget or 0) > 0
	else
		return #bottomSpells == #bottomSpellsPlaceHolder
	end
end

function contingencyDoneButtonText()
	if contingencyComplete() then
		return t("DONE_BUTTON")
	else
		return t("CANCEL_BUTTON")
	end
end

function filterMemorizedMageSpells()
	local out = {}
	currentSpellLevel = math.min(currentSpellLevel, 9)
	for k,v in pairs(characters[id].mageSpells[currentSpellLevel]) do
		for i=v.memorizedCount, 1, -1 do
			local spell = deepcopy(v)
			if(i <= v.castableCount) then
				spell.castable = 1
			else
				spell.castable = 0
			end
			table.insert(out, spell)
		end
	end
	return out
end

function tableInsert(out, v)
	if mageScreen:SpellSwappedInContingency(v.resref) then
		for key,value in pairs(contingencySwapTable) do
			value.castableCount = v.castableCount
			table.insert(out, value)
		end
	else
		table.insert(out, v)
	end
end

function Redirect_filterContingencyMageSpells()
	local out = {}
	if characters[id].mageSpells ~= nil and characters[id].mageSpells[currentSpellLevel] ~= nil then
		for k,v in pairs(characters[id].mageSpells[currentSpellLevel]) do
			if v.castableCount > 0 and mageScreen:SpellAllowedForContingency(v.level, v.resref) then
				tableInsert(out, v)
			end
		end
	end
	if characters[id].priestSpells ~= nil and characters[id].priestSpells[currentSpellLevel] ~= nil then
		for k,v in pairs(characters[id].priestSpells[currentSpellLevel]) do
			if v.castableCount > 0 and mageScreen:SpellAllowedForContingency(v.level, v.resref) then
				tableInsert(out, v)
			end
		end
	end
	return out
end

function findFirstDifferenceInSpellList(oldList, newList)
	local ret = -1
	local spellIndex = 1

	if oldList ~= nil and newList ~= nil then
		while oldList[spellIndex] ~= nil do
			if newList[spellIndex] == nil then
				ret = spellIndex
				break
			end
			if oldList[spellIndex].icon ~= newList[spellIndex].icon then
				ret = spellIndex
				break
			end
			spellIndex = spellIndex + 1
		end
		if oldList[spellIndex] == nil and newList[spellIndex] ~= nil then
			ret = spellIndex
		end
	end

	return ret
end

showMageMemorizationFlash = false

function refreshMageBook()
	if currentSpellLevel == nil then
		currentSpellLevel = 1
	end
	if bookMode == 0 then
		if characters[id].hasMageBook then
			bookSpells = characters[id].mageSpells[currentSpellLevel]
			newBottomSpells = filterMemorizedMageSpells()
			
			if showMageMemorizationFlash == true then
				createMageMemorizationSparkle(0,0,36,36,"memorizedListMage", findFirstDifferenceInSpellList(bottomSpells, newBottomSpells))
				showMageMemorizationFlash = false
			end
			bottomSpells = newBottomSpells
			bottomSpellsPlaceHolder = makeBlankTable(characters[id].mageDetails[currentSpellLevel].maxMemorized) 
		else
			bookSpells = characters[id].mageSpells[currentSpellLevel]
			bottomSpells = {}
			bottomSpellsPlaceHolder = {}
		end
	elseif bookMode == 1 then
		bookSpells = filterContingencyMageSpells()
		bottomSpells = sequencerSpells
		bottomSpellsPlaceHolder = makeBlankTable(contingencyMaxSpells) 
		contingencyDescription = mageBookStrings[contingencyResRef].tip
	end
end

function setMageBookLevel(num)
	lastCurrentBookSpell = 0
	currentBookSpell = 0
	currentSpellLevel = num
	mageScreen:SetSpellLevel(num-1)
	refreshMageBook()
end

currentAnimationID = 1
updateCounterMemorizationSparkles = 1

function updateMemorizationSparkles()
	local sparkleNumber = 1
	updateCounterMemorizationSparkles = updateCounterMemorizationSparkles + 1
	if updateCounterMemorizationSparkles > 2 then
		updateCounterMemorizationSparkles = 1
		for sparkleNumber = 1, #(memorizationFlashes), 1 do
			if memorizationFlashes[sparkleNumber][1] == true then
				memorizationFlashes[sparkleNumber][2] = memorizationFlashes[sparkleNumber][2] + 1
				if memorizationFlashes[sparkleNumber][2] > 7 then
					memorizationFlashes[sparkleNumber][1] = false
					memorizationFlashes[sparkleNumber][2] = 0
					memorizationFlashes[sparkleNumber][3] = true
				end
			end
		end
	end
end

function destroyMemorizationSparkle(instanceId)
	local ret = memorizationFlashes[instanceId][3]
	memorizationFlashes[instanceId][3] = false
	return ret
end

function showMemorizationSparkle(instanceId)
	updateMemorizationSparkles()
	return memorizationFlashes[instanceId][1]
end

function createMageMemorizationSparkle(x,y,w,h, fromList, listIndex)
	Infinity_InstanceAnimation("TEMPLATE_mageMemorizationSparkle","FLASHBR",x,y,w,h,fromList,listIndex)
	memorizationFlashes[currentAnimationID][1] = true
	memorizationFlashes[currentAnimationID][3] = false
	currentAnimationID = currentAnimationID + 1
	if currentAnimationID > #(memorizationFlashes) then
		currentAnimationID = 1
	end
end

function findMemorizedUncastable(resref)
	local index = 1
	local sparkle = -1
	for index = 1, #(bottomSpells), 1 do
		if bottomSpells[index].resref == resref then
			if bottomSpells[index].castable == 0 then
				sparkle = index
				break
			end
		end
	end

	return sparkle
end

function unmemorizingMageSpell(resref)
	local index = 1
	local sparkle = -1
	for index = 1, #(bottomSpells), 1 do
		if bottomSpells[index].resref == resref then
			sparkle = index
			if bottomSpells[index].castable == 0 then
				break
			end
		end
	end

	createMageMemorizationSparkle(0, 0, 36, 36, 'memorizedListMage', sparkle)
end

function unmemorizeMageSpell(slot)
	showMageMemorizationFlash = false
	mageScreen:UnmemorizeSpell( bottomSpells[slot].level, bottomSpells[slot].memorizedIndex )
	Infinity_PlaySound('GAM_44')
end

memorizationFlashes = 
{
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false},
	{false, 0, false}
}

`


menu
{
	name 'MAGE'
	align center center
	modal lua "bookMode == 1"

	onopen "
		showMageMemorizationFlash = false
		mgpage = nil
		setMageBookLevel(1)
		if showContingency then
			Infinity_SetArea('bookListMage', nil, 412, nil, 156)
			Infinity_SetArea('bookDescription', nil, 412, nil, 156)
		else
			Infinity_SetArea('bookListMage', nil, 186, nil, 384)
			Infinity_SetArea('bookDescription', nil, 186, nil, 384)
		end
		if bookMode == 1 then
			contingencyDescription = mageBookStrings[contingencyResRef].tip
		end
		currentContingencyCondition = 0
		currentContingencyTarget = 0
		currentAnimationID = 1
		updateCounterMemorizationSparkles = 1
		"
	onclose "
	"

	button
	{
		enabled 	"CurrentlyInGame()"
		on escape
		action
		"
			--Return to world screen on escape 
			e:SelectEngine(worldScreen)
		"
	}

	template
	{
		label
		{
			enabled "showMemorizationSparkle(instanceId)"
			ignoreEvents
			area 0 0 45 42
			bam "FLASHBR"
			usealpha lua "true"
			frame lua "memorizationFlashes[instanceId][2]"
			align center center
		}
		name "TEMPLATE_mageMemorizationSparkle"
	}



	label
	{
		area 0 0 864 710
		mosaic "GUIMGB"
	}
	label
	{
		area		82 10 700 44
		text lua	"mageBookTitle()"
		text style	"title"
	}
	label
	{
		area 		210 59 446 30
		text lua	"mageBookAction()"
		text style	"label"
	}
	button
	{
		area		168 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	0
		enabled		"maxMagePage > 0"
		action		"setMageBookLevel(1)"
	}
	button
	{
		area		227 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	1
		enabled		"maxMagePage > 1"
		action		"setMageBookLevel(2)"
	}
	button
	{
		area		286 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	2
		enabled		"maxMagePage > 2"
		action		"setMageBookLevel(3)"
	}
	button
	{
		area		345 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	3
		enabled		"maxMagePage > 3"
		action		"setMageBookLevel(4)"
	}
	button
	{
		area		404 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	4
		enabled		"maxMagePage > 4"
		action		"setMageBookLevel(5)"
	}
	button
	{
		area		464 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	5
		enabled		"maxMagePage > 5"
		action		"setMageBookLevel(6)"
	}
	button
	{
		area		523 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	6
		enabled		"maxMagePage > 6"
		action		"setMageBookLevel(7)"
	}
	button
	{
		area		583 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	7
		enabled		"maxMagePage > 7"
		action		"setMageBookLevel(8)"
	}
	button
	{
		area		644 110 54 54
		bam		GUIPRTC
		highlightgroup	mgpage
		sequence	8
		enabled		"maxMagePage > 8"
		action		"setMageBookLevel(9)"
	}

	list
	{
		column 
		{ 
			width 15
			label
			{
				area	0 0 -1 -1
				bam	lua "bookSpells[rowNumber].icon"
				align	center center
			}
		}
		column 
		{ 
			width 85
			label
			{
				area		0 0 -1 -1
				text lua "Infinity_FetchString( bookSpells[rowNumber].name)"
				text style "normal_parchment"
				text align left center
			}
		}

		area 112 412 302 156
		
		name 		"bookListMage"
		rowheight	40
		table		"bookSpells"
		var		currentBookSpell
		scrollbar	'GUISCRC'
		action		
		"
			contingencyDescription = 0
			if cellNumber == 1 then
				if bookMode == 0 then
					if #bottomSpells < #bottomSpellsPlaceHolder then
						createMageMemorizationSparkle(0, 0, 40, 40, 'bookListMage', -1)
						Infinity_PlaySound('GAM_24')
						showMageMemorizationFlash = true
					end
					mageScreen:MemorizeSpell( bookSpells[currentBookSpell].level, bookSpells[currentBookSpell].index )
				elseif bookMode == 1 and #bottomSpells < #bottomSpellsPlaceHolder then
					mageScreen:SequenceSpell( bookSpells[currentBookSpell].resref, bookSpells[currentBookSpell].masterResref )
				end
			end
			if lastCurrentBookSpell == currentBookSpell and cellNumber == 2 then
				currentBookSpell = 0
				contingencyDescription = mageBookStrings[contingencyResRef].tip
			else
				lastCurrentBookSpell = currentBookSpell
			end
		"
		actionalt
		"
			if cellNumber == 1 and bookMode == 0 and characters[id].hasSorcererBook == false then
				popup2Button(63745, 'REMOVE_BUTTON', function() mageScreen:EraseKnownSpell(bookSpells[currentBookSpell].resref) end)
			end
		"

	}
	label
	{
		area 146 178 268 224
		rectangle 1
		rectangle opacity 200 
		enabled "showContingency"
	}

	label
	{
		area 152 182 262 28
		enabled "showContingency"
		text "CONDITION_NORMAL"
		text style "normal"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area		10 0 -1 -1
				text lua "Infinity_FetchString( contingencyConditions[rowNumber].strref)"
				text style "normal"
				text align left center
			}
		}

		area 152 210 262 186
		
		enabled 	"showContingency"
		rowheight	40
		table		"contingencyConditions"
		var		currentContingencyCondition
		scrollbar	'GUISCRC'
		action
		"
			contingencyDescription = contingencyConditions[currentContingencyCondition].desc
		"

	}
	label
	{
		area 452 176 254 226
		rectangle 1
		rectangle opacity 200 
		enabled "showContingency"
	}
	label
	{
		area 458 182 240 28
		enabled "showContingency"
		text "TARGET_NORMAL"
		text style "normal"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area		10 0 -1 -1
				text lua "Infinity_FetchString( contingencyTargets[rowNumber].strref)"
				text style "normal"
				text align left center
			}
		}

		area 458 210 240 186
		
		enabled 	"showContingency"
		rowheight	40
		table		"contingencyTargets"
		var		currentContingencyTarget
		scrollbar	'GUISCRC'
		action
		"
			contingencyDescription = contingencyTargets[currentContingencyTarget].desc
		"
	}

	text
	{
		name		"bookDescription"
		area		448 412 322 156
		text lua 	"mageBookDescription()"
		text style	"normal_parchment"
		scrollbar	'GUISCRC'
	}

	list
	{
		column 
		{ 
			width 100
			label
			{
				area	0 0 -1 -1
				bam	"SPELFRMS"
				sequence 0
				align	center center
			}
		}

		area 70 654 718 36
		
		enabled "#bottomSpellsPlaceHolder ~= 0 or bookMode == 1"
		rowwidth	36
		table		"bottomSpellsPlaceHolder"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area	0 0 -1 -1
				bam	lua "bottomSpells[rowNumber].icon"
				align	center center
				greyscale lua "bottomSpells[rowNumber].castable == 0"
			}
		}

		area 70 654 718 36
		
		name 		"memorizedListMage"
		enabled 	"#bottomSpells ~= 0"
		rowwidth	36
		table		"bottomSpells"
		var		currentBottomSpell
		action		
		"
			if bookMode == 0 then
				if findMemorizedUncastable(bottomSpells[currentBottomSpell].resref) == -1 and Infinity_GetOption(41, 9) ~= 0 then
					popup2Button(11824, 'REMOVE_BUTTON', function() unmemorizeMageSpell(currentBottomSpell) end, 'CANCEL_BUTTON')
				else
					unmemorizeMageSpell(currentBottomSpell)
				end
			elseif bookMode == 1 then
				mageScreen:UnSequenceSpell( bottomSpells[currentBottomSpell].resref, bottomSpells[currentBottomSpell].masterResref )
				table.remove(sequencerSpells, currentBottomSpell)
				bottomSpells = sequencerSpells
				currentBottomSpell = 0
			end
		"
	}


	label
	{
		area 296 588 272 42
		text lua "magePageInfo()"
		text style "label"
		rectangle 0
	}

	button
	{
		area 588 584 236 52
		enabled "bookMode == 0 and (#characters[id].contingencySpells > 0 or #characters[id].sequencerSpells > 0)"
		bam GUIOSTLR
		text "CONTINGENCY_BUTTON"
		text style "button"
		action "Infinity_PushMenu('MAGE_CONTINGENCY')"
		
	}
	button
	{
		area 60 588 236 52
		bam GUIOSTLL
		enabled "bookMode == 1 or characters[id].hasMageBook"
		clickable lua "#bottomSpells < #bottomSpellsPlaceHolder and currentBookSpell ~= 0"
		text "MEMORIZE_BUTTON"
		text style "button"
		action 
		"
			if bookMode == 0 then
				createMageMemorizationSparkle(0, 0, 40, 40, 'bookListMage', -1)
				showMageMemorizationFlash = true
				Infinity_PlaySound('GAM_24')
				mageScreen:MemorizeSpell( characters[id].mageSpells[currentSpellLevel][currentBookSpell].level, characters[id].mageSpells[currentSpellLevel][currentBookSpell].index )
			elseif bookMode == 1 then
				mageScreen:SequenceSpell( bookSpells[currentBookSpell].resref, bookSpells[currentBookSpell].masterResref )
			end

		"
		
	}

	button
	{
		area 572 588 236 52
		enabled "bookMode == 1"
		bam GUIOSTLR
		text lua "contingencyDoneButtonText()"

		text style "button"
		action 
		"
			if contingencyComplete() then
				mageScreen:DoneSequencingSpells()
			else
				mageScreen:CancelSequencingSpells()
			end
			e:SelectEngine(worldScreen)
		"
		
	}

	label
	{
		area 0 0 865 710
		fill        0 0 0 176
		enabled "mageBookEnabled == false and bookMode == 0"
	}

}

`
function refreshMageContingency()
	preparedSpells = {}
	for k, v in pairs(characters[id].contingencySpells) do
		table.insert(preparedSpells, v)
	end
	for k, v in pairs(characters[id].sequencerSpells) do
		table.insert(preparedSpells, v)
	end

end
`

menu
{
	name 'MAGE_CONTINGENCY'

	align center center
	modal

	onopen "refreshMageContingency()"
	
	label
	{
		area 0 0 864 710 
		mosaic "GUIMGCP"
	}
	label --Title
	{
		area 40 104 790 106
		text "SPELLS_PREPARED_LABEL"
		text style "label"
		text align left top
	}
	label
	{
		area 78 14 710 44
		text "CONTINGENCY_TITLE"
		text style "title"
	}
	label
	{
		area 238 258 190 36
		text "CONDITION_LABEL"
		text style "label"
		text align left center
	}
	label
	{
		area 428 258 200 36
		text "TARGET_LABEL"
		text style "label"
		text align left center
	}

	label
	{
		area 628 258 196 36
		text "SPELL_LABEL"
		text style "label"
		text align left center
	}

	list
	{
		column
		{
			width 25
			label
			{
				area	0 0 -1 -1
				text lua "t(mageBookStrings[preparedSpells[rowNumber].resref].title)"
				text style "label"
				align	left center
			}

		}
		column
		{
			width 25
			label
			{
				area	0 0 -1 -1
				text lua "Infinity_FetchString(preparedSpells[rowNumber].condition)"
				text style "label"
				align	left center
			}

		}
		column
		{
			width 25
			label
			{
				area	0 0 -1 -1
				text lua "Infinity_FetchString(preparedSpells[rowNumber].target)"
				text style "label"
				align	left center
			}

		}

		column 
		{ 
			width 5
			label
			{
				enabled "preparedSpells[rowNumber].spells[1] ~= nil"
				area	0 0 -1 -1
				bam	lua "preparedSpells[rowNumber].spells[1].icon"
				align	center center
			}
		}
		column 
		{ 
			width 5
			label
			{
				enabled "preparedSpells[rowNumber].spells[2] ~= nil"
				area	0 0 -1 -1
				bam	lua "preparedSpells[rowNumber].spells[2].icon"
				align	center center
			}
		}
		column 
		{ 
			width 5
			label
			{
				enabled "preparedSpells[rowNumber].spells[3] ~= nil"
				area	0 0 -1 -1
				bam	lua "preparedSpells[rowNumber].spells[3].icon"
				align	center center
			}
		}
		column 
		{ 
			width 5
			label
			{
				area	0 0 -1 -1
				bam	"GUISTMPC"
				sequence 2
				align	center center
				enabled "preparedSpells[rowNumber].dispellable"
			}
		}

		area 44 294 780 300
		
		rowheight	56
		table		"preparedSpells"
		var		"currentContingencySpell"
		action		"
			if (cellNumber == 7) and preparedSpells[currentContingencySpell].dispellable then
				popup2Button(32665, 'YES_BUTTON', function() mageScreen:OnDispellButtonClick(currentContingencySpell) end, 'NO_BUTTON')
			end
		"
	}
	

	button
	{
		area 294 656 302 44
		bam GUIOSTCL
		text "DONE_BUTTON"
		text style "button"
		action "Infinity_PopMenu('MAGE_CONTINGENCY')"
	}
}

menu
{
	name "POPUP_DETAILS"
	align center center
	modal

	label
	{
		area 0 0 864 710
		mosaic "GUIINVHI"
	}
	label
	{
		area 82 10 700 44
		text lua "Infinity_FetchString(PopupDetails.title)"
		text style "title"
	}
	label
	{
		area 310 65 310 50
		text lua "Infinity_FetchString(PopupDetails.name)"
		text style "label"
	}
	text
	{
		area 62 178 736 348
		text lua "Infinity_FetchString(PopupDetails.description)"
		text style "parchment"
		scrollbar 'GUISCRC'
	}
	label
	{
		area 254 65 52 52
		bam lua "PopupDetails.icon"
		align center center
		sequence 0
	}
	button
	{
		area 326 638 205 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		
		on escape
		action
		"
			Infinity_PopMenu('POPUP_DETAILS')
		"
	}

}


`
function priestPageInfo()
	if characters[id].hasShamanBook then
		return t("SPELLS_CAN_CAST_LABEL") .. ": " .. characters[id].priestDetails[currentSpellLevel].slotsRemaining .. "/" .. characters[id].priestDetails[currentSpellLevel].maxMemorized
	else
		return t("MEMORIZED_LABEL") .. ": " .. #bottomSpells .. "/" .. characters[id].priestDetails[currentSpellLevel].maxMemorized
	end
end

function priestBookDescription()
	if priestBookEnabled == true then
		if characters[id].priestSpells[currentSpellLevel][currentBookSpell] then
			return Infinity_FetchString(characters[id].priestSpells[currentSpellLevel][currentBookSpell].description)
		else
			return t('SPELL_MEMORIZATION_HELP')
		end
	end
	return ""
end

function filterMemorizedPriestSpells()
	local out = {}
	currentSpellLevel = math.min(currentSpellLevel, 7)
	for k,v in pairs(characters[id].priestSpells[currentSpellLevel]) do
		for i=v.memorizedCount, 1, -1 do
			local spell = deepcopy(v)
			if(i <= v.castableCount) then
				spell.castable = 1
			else
				spell.castable = 0
			end
			table.insert(out, spell)
		end
	end
	return out
end

showPriestMemorizationFlash = false

function refreshPriestBook()
	if currentSpellLevel == nil then
		currentSpellLevel = 1
	end
	if characters[id].hasClericBook then
		newBottomSpells = filterMemorizedPriestSpells()

		if showPriestMemorizationFlash == true then
			createPriestMemorizationSparkle(0,0,36,36,"memorizedListPriest", findFirstDifferenceInSpellList(bottomSpells, newBottomSpells))
			showPriestMemorizationFlash = false
		end
		bottomSpells = newBottomSpells
		bottomSpellsPlaceHolder = makeBlankTable(characters[id].priestDetails[currentSpellLevel].maxMemorized) 
	else
		bottomSpells = {}
		bottomSpellsPlaceHolder = {}
	end
end

function setPriestBookLevel(num)
	lastCurrentBookSpell = 0
	currentBookSpell = 0
	currentSpellLevel = num
	refreshPriestBook()
end

function createPriestMemorizationSparkle(x,y,w,h, fromList, listIndex)
	Infinity_InstanceAnimation("TEMPLATE_priestMemorizationSparkle","FLASHBR",x,y,w,h,fromList,listIndex)
	memorizationFlashes[currentAnimationID][1] = true
	memorizationFlashes[currentAnimationID][3] = false
	currentAnimationID = currentAnimationID + 1
	if currentAnimationID > #(memorizationFlashes) then
		currentAnimationID = 1
	end
end

function unmemorizingPriestSpell(resref)
	local index = 1
	local sparkle = -1
	for index = 1, #(bottomSpells), 1 do
		if bottomSpells[index].resref == resref then
			sparkle = index
			if bottomSpells[index].castable == 0 then
				break
			end
		end
	end

	createPriestMemorizationSparkle(0, 0, 36, 36, 'memorizedListPriest', sparkle)
end

function unmemorizePriestSpell(slot)
	showPriestMemorizationFlash = false
	priestScreen:UnmemorizeSpell( bottomSpells[slot].level, bottomSpells[slot].memorizedIndex )
	Infinity_PlaySound('GAM_44')
end

`
menu
{
	name 'PRIEST'
	align center center

	onopen 
	"
		showPriestMemorizationFlash = false
		pushSidebars()
		prpage = nil
		setPriestBookLevel(1)
		currentAnimationID = 1
		updateCounterMemorizationSparkles = 1
	"
	onclose 
	"
		popSidebars()
	"

	button
	{
		on escape
		action
		"
			--Return to world screen on escape 
			e:SelectEngine(worldScreen)
		"
	}

	template
	{
		label
		{
			enabled "showMemorizationSparkle(instanceId)"
			ignoreEvents
			area 0 0 45 42
			bam "FLASHBR"
			usealpha lua "true"
			frame lua "memorizationFlashes[instanceId][2]"
			align center center
		}
		name "TEMPLATE_priestMemorizationSparkle"
	}



	label
	{
		area 0 0 864 710
		mosaic "GUIPRB"
	}
	label
	{
		area		82 10 700 44
		text		"PRIEST_SCROLL_TITLE" 
		text style	"title"
	}
	label
	{
		area 		210 59 446 30
		text lua	"priestName"
		text style	"label"
	}
	button
	{
		area		168 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	0
		enabled		"maxPriestPage > 0"
		action		"setPriestBookLevel(1)"
	}
	button
	{
		area		246 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	1
		enabled		"maxPriestPage > 1"
		action		"setPriestBookLevel(2)"
	}
	button
	{
		area		328 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	2
		enabled		"maxPriestPage > 2"
		action		"setPriestBookLevel(3)"
	}
	button
	{
		area		403 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	3
		enabled		"maxPriestPage > 3"
		action		"setPriestBookLevel(4)"
	}
	button
	{
		area		484 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	4
		enabled		"maxPriestPage > 4"
		action		"setPriestBookLevel(5)"
	}
	button
	{
		area		566 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	5
		enabled		"maxPriestPage > 5"
		action		"setPriestBookLevel(6)"
	}
	button
	{
		area		642 110 54 54
		bam		GUIPRTC
		highlightgroup	prpage
		sequence	6
		enabled		"maxPriestPage > 6"
		action		"setPriestBookLevel(7)"
	}

	list
	{
		column 
		{ 
			width 15
			label
			{
				area	0 0 -1 -1
				bam	lua "characters[id].priestSpells[currentSpellLevel][rowNumber].icon"
				align	center center
			}
		}
		column 
		{ 
			width 85
			label
			{
				area		0 0 -1 -1
				text lua "Infinity_FetchString( characters[id].priestSpells[currentSpellLevel][rowNumber].name)"
				text style "normal_parchment"
				text align left center
			}
		}

		area 82 182 326 370
		
		name "bookListPriest"
		rowheight	40
		table		"characters[id].priestSpells[currentSpellLevel]"
		var		currentBookSpell
		scrollbar	'GUISCRC'
		action		"
			if cellNumber == 1 then
				if #bottomSpells < #bottomSpellsPlaceHolder then
					createPriestMemorizationSparkle(0, 0, 40, 40, 'bookListPriest', -1)
					Infinity_PlaySound('GAM_24')
					showPriestMemorizationFlash = true
				end
				priestScreen:MemorizeSpell( characters[id].priestSpells[currentSpellLevel][currentBookSpell].level, characters[id].priestSpells[currentSpellLevel][currentBookSpell].index )
			end
			if lastCurrentBookSpell == currentBookSpell and cellNumber == 2 then
				currentBookSpell = 0
			else
				lastCurrentBookSpell = currentBookSpell
			end
		"

	}

	text
	{
		area		438 182 340 370
		text lua 	"priestBookDescription()"
		text style	"normal_parchment"
		scrollbar	'GUISCRC'
	}

	list
	{
		column 
		{ 
			width 100
			label
			{
				area	0 0 -1 -1
				bam	"SPELFRMS"
				sequence 0
				align	center center
			}
		}

		area 70 654 718 36
		
		rowwidth	36
		table		"bottomSpellsPlaceHolder"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area	0 0 -1 -1
				bam	lua "bottomSpells[rowNumber].icon"
				align	center center
				greyscale lua "bottomSpells[rowNumber].castable == 0"
			}
		}

		area 70 654 718 36
		
		name "memorizedListPriest"
		enabled 	"#bottomSpells ~= 0"
		rowwidth	36
		table		"bottomSpells"
		var		currentBottomSpell
		action		
		"
			if bottomSpells[currentBottomSpell] then
				if findMemorizedUncastable(bottomSpells[currentBottomSpell].resref) == -1 and Infinity_GetOption(41, 9) ~= 0 then
					popup2Button(11824, 'REMOVE_BUTTON', function() unmemorizePriestSpell(currentBottomSpell) end, 'CANCEL_BUTTON')
				else
					unmemorizePriestSpell(currentBottomSpell)
				end
			end
		"
	}


	label
	{
		area 272 598 276 40
		text lua "priestPageInfo()"
		text style "label"
		rectangle 0
	}

	button
	{
		area 60 594 204 44
		bam GUIOSTLM
		enabled "characters[id].hasClericBook"
		clickable lua "#bottomSpells < characters[id].priestDetails[currentSpellLevel].maxMemorized and currentBookSpell ~= 0"
		text "MEMORIZE_LABEL"
		text style "button"
		action 
		"
			createPriestMemorizationSparkle(0, 0, 40, 40, 'bookListPriest', -1)
			Infinity_PlaySound('GAM_24')
			showPriestMemorizationFlash = true
			priestScreen:MemorizeSpell( characters[id].priestSpells[currentSpellLevel][currentBookSpell].level, characters[id].priestSpells[currentSpellLevel][currentBookSpell].index )

		"
		
	}

	label
	{
		area 0 0 865 710
		fill        0 0 0 176
		enabled "priestBookEnabled == false"
	}
}
`
	versionString = ""
	function canClickSaveLoad()
		return game:IsClient() == false
	end
`
menu
{
	name "ESC_MENU"
	ignoreesc
	align center center
	onOpen "
		versionString = CBaldurChitin:GetVersionString()
		pushSidebars()
	"
	onClose "popSidebars()"
	label
	{
		area 0 0 864 768
		mosaic STONEOPT
	}
	label
	{
		area 258 114 350 44
		text "OPTIONS_TITLE"
		text style "title"
	}
	label
	{
		area 244 145 378 29
		text lua "versionString"
		text style "normal"
		text align center center
	}
	button
	{
		area 570 442 260 76
		bam 'STARTMBT'
		sequence 5
		pad 10 8 10 8
		text style "button"
		text 		"GAMEPLAY_BUTTON"
		text style	"button"
		
		action
		"
			Infinity_PushMenu( 'OPTIONS_GAMEPLAY' )

		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 4
		area 597 354 233 84
		pad 10 8 10 8
		text style "button"
		text 		"GRAPHICS_BUTTON"
		text style	"button"
		
		action
		"
			Infinity_PushMenu( 'OPTIONS_GRAPHICS' )

		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 3
		area 564 276 266 74
		pad 10 8 10 8
		text style "button"
		text 		"SOUND_BUTTON"
		text style	"button"
		
		action
		"
			Infinity_PushMenu( 'OPTIONS_SOUND' )

		"
	}
	button
	{
		area 284 628 300 45
		bam GUIOSTCL
		text "RETURN_GAME_BUTTON"
		text style "button"
		action
		"
			e:SelectEngine( worldScreen );
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 0
		area 32 276 262 74
		pad 10 8 10 8
		text style "button"
		text "LOAD_GAME_BUTTON"
		clickable lua "canClickSaveLoad()"
		action
		"
			popup2Button(19531, 'LOAD_BUTTON', function() optionsScreen:LoadGame() end)
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 1
		area 32 354 236 84
		pad 10 8 10 8
		text style "button"
		text "QUIT_GAME_BUTTON"
		action
		"
			if e:IsTouchUI() then
				popup3Button(16456, 
				'CANCEL_BUTTON', nil, 
				'MAIN_MENU_BUTTON', function() optionsScreen:QuitGame() end, 
				'SAVE_BUTTON', function() optionsScreen:SaveGame(0) end
				)
			else
				popup4Button(16456, 
				'CANCEL_BUTTON', nil, 
				'MAIN_MENU_BUTTON', function() optionsScreen:QuitGame() end, 
				'QUIT_BUTTON', function() Infinity_ShutdownGame() end, 
				'SAVE_BUTTON', function() optionsScreen:SaveGame(0) end
				)
			end
		"
	}
	button
	{
		bam 'STARTMBT'
		sequence 2
		area 32 442 262 76
		pad 10 8 10 8
		text style "button"
		text "SAVE_GAME_BUTTON"
		clickable lua "canClickSaveLoad()"
		action
		"
			optionsScreen:SaveGame(0)
		"
	}
	
	label
	{
		area 244 174 378 454
		bam 'BIGLOGO'
		align center center
		frame lua 'logoFrame'
	}
}

`
OptionsButtons = 
{
	{text = "GAMEPLAY_BUTTON", menu = "OPTIONS_GAMEPLAY", sequence = 0}, 
	{text = "GRAPHICS_BUTTON", menu = "OPTIONS_GRAPHICS", sequence = 1}, 
	{text = "LANGUAGE_BUTTON", menu = "OPTIONS_LANGUAGE", sequence = 0}, 
	{text = "MOVIES_BUTTON", menu = "", sequence = 2}, 
	{text = "SOUND_BUTTON", menu = "OPTIONS_SOUND", sequence = 1}, 
}
`
menu
{
	name 'START_OPTIONS'
	align center center
	ignoreEsc

	label
	{
		area 0 0 1024 768
		mosaic 'START'
	}
	label
	{
		area 112 26 786 202	
		bam 'TITLE'
		sequence 0
		align center center
		frame lua 'logoFrame'
	}
	label
	{
		area 338 192 352 456	
		bam 'BIGLOGO'
		align center center
		frame lua 'logoFrame'
	}

	button
	{
		bam 'STARTMBT'
		sequence 0
		area 112 294 262 74
		pad 10 8 10 8
		text style "button"
		text "SOUND_BUTTON"
		action "Infinity_PushMenu( 'OPTIONS_SOUND' )"
	}
	button
	{
		bam 'STARTMBT'
		sequence 3
		area 649 300 266 74
		pad 10 8 10 8
		text style "button"
		text "GRAPHICS_BUTTON"
		action "Infinity_PushMenu( 'OPTIONS_GRAPHICS' )"
	}
	button
	{
		bam 'STARTMBT'
		sequence 1
		area 112 374 236 84
		pad 10 8 10 8
		text style "button"
		text "LANGUAGE_BUTTON"
		action "Infinity_PushMenu( 'OPTIONS_LANGUAGE' )"
	}
	button
	{
		bam 'STARTMBT'
		sequence 4
		area 682 378 233 84
		pad 10 8 10 8
		text style "button"
		text "MOVIES_BUTTON"
		action "e:SelectEngine(moviesScreen)"
	}
	button
	{
		bam 'STARTMBT'
		sequence 2
		area 116 462 262 76
		pad 10 8 10 8
		text style "button"
		text "GAMEPLAY_BUTTON"
		action "Infinity_PushMenu( 'OPTIONS_GAMEPLAY' )"
	}
	button
	{
		on escape
		area 649 462 260 76
		bam 'STARTMBT'
		sequence 5
		pad 10 8 10 8
		text style "button"
		text "BACK_BUTTON"
		action
		"
			Infinity_PopMenu()
			e:SelectEngine(startEngine)
		"
	}
}
`
mapnoteSettings = {}
showNotes = 1
function showNote(instanceId)
	if(mapScreen:IsNoteVisible(mapnoteSettings[instanceId].worldCoord.x, mapnoteSettings[instanceId].worldCoord.y)
	and mapnoteSettings[instanceId].screenCoord.x >= 0
	and mapnoteSettings[instanceId].screenCoord.y >= 0) then
		return showNotes
	else
		return false
	end
end
notesAlpha = 0
function getAndIncrementNotesAlpha()
	if(notesAlpha < .99) then
		notesAlpha = notesAlpha + 0.075
	end
	if(notesAlpha > 1) then
		notesAlpha = 1
	end
	return notesAlpha
end
`
menu
{
	name 'AREA_MAP_TITLE'
	align center top
	opacity lua "notesAlpha"
	ignoreEsc
	label
	{
		name "AREA_MAP_BACKGROUND"
		area 66 0 662 92
		rectangle 0
	}
	label
	{
		area 74 8 184 74
		name "AREA_MAP_TITLE"
		text "AREA_MAP_TITLE"
		text style title
	}
		label
	{
		area 300 8 170 36
		action "mapScreen:ToggleDisplayExploredMap()"
		text "WORLDMAP_HIGHLIGHT_LABEL"
		text style "label"
		text align left center

	}
	button
	{
		area 264 8 206 36
		bam "4CHECK"
		sequence lua "mapScreen:DisplayExploredMap() and 0 or 1"
		action "mapScreen:ToggleDisplayExploredMap()"
	}

	label
	{
		area 300 42 170 40
		toggle showNotes
		text "WORLD_MAP_NOTES_LABEL"
		text style "label"
		text align left center

	}
	button
	{
		area 264 42 206 40
		bam "4CHECK"
		sequence lua "showNotes == 1 and 0 or 1"
		toggle showNotes
	}

	button
	{
		area 500 24 200 44
		bam GUIOSTLM
		sequence 0
		text style "button"
		text "WORLD_MAP_BUTTON"
		action
		"
			worldMapScreen:StartWorldMap(0)
			e:SelectEngine(worldMapScreen)
		"
	}

}
`
	areaMapHover = -1
	function showAreaMapNoteTooltip(id)
		if id == areaMapHover then
			return true
		else
			return false
		end
	end
`
menu
{
	name 'AREA_MAP'
	align left top
	ignoreesc
	onOpen "pushSidebars(); Infinity_PushMenu('AREA_MAP_TITLE'); notesAlpha = 0"
	onClose "popSidebars(); Infinity_PopMenu('AREA_MAP_TITLE');"
	opacity lua "getAndIncrementNotesAlpha()"
	template
	{
		button
		{
			enabled "showNote(instanceId)"
			area 0 0 45 42
			bam "FLAG1"
			sequence lua "mapnoteSettings[instanceId].sequence"
			tooltip force lua "showAreaMapNoteTooltip(instanceId)"
			tooltip force top
			tooltip lua "Infinity_FetchString(mapnoteSettings[instanceId].text)"
			tooltip position 3
			actionAlt
			"
				mapScreen:OnUserNoteClick(instanceId, mapnoteSettings[instanceId].worldCoord.x, mapnoteSettings[instanceId].worldCoord.y)
				Infinity_PushMenu('NOTE_ADD',0,0)
			"
			actionEnter
			"
				areaMapHover = instanceId
			"
			actionExit
			"
				areaMapHover = -1
			"
		}
		name "TEMPLATE_mapnote"
	}
}
`
	colorChoice = nil
`
menu
{
	name 'NOTE_ADD'
	align center center
	onOpen 
	"
		if colorChoice == nil then
			colorChoice = Infinity_FindUIItemByName('BUTTON_mapNoteColor_' .. mapScreen:GetColorChoice())
		end
	"
	onClose
	"
		colorChoice = nil
	"
	modal
	label
	{
		area 0 0 900 234
		mosaic GUIERR7
	}
	label
	{
		area	 32 24 840 50
		rectangle	0
	}
	edit
	{
		name 		"mapNoteEditArea"
		area		40 32 818 34
		var			mapNoteEdit
		scrollbar	'GUISCRC'
		text style	"edit"
	}
	button
	{
		area 640 166 200 44
		bam GUIOSTLM
		text style "button"
		text "DONE_BUTTON"
		action
		"
			mapScreen:OnUserNoteDoneButtonClick()
			Infinity_PopMenu('NOTE_ADD',0,0)
		"
	}
	button
	{
		area 342 166 200 44
		bam GUIOSTLM
		text style "button"
		text "CANCEL_BUTTON"
		action
		"
			Infinity_PopMenu('NOTE_ADD',0,0)
		"
	}
	button
	{
		area 52 166 200 44
		bam GUIOSTLM
		text style "button"
		text "DELETE_BUTTON"
		action
		"
			mapScreen:OnUserNoteDeleteButtonClick()
			Infinity_PopMenu('NOTE_ADD',0,0)
		"
	}
	
	button
	{
		name "BUTTON_mapNoteColor_0"
		area 240 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 0
		action
		"
			mapScreen:OnColorChoice(0)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_1"
		area 316 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 1
		action
		"
			mapScreen:OnColorChoice(1)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_2"
		area 392 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 2
		action
		"
			mapScreen:OnColorChoice(2)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_3"
		area 470 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 3
		action
		"
			mapScreen:OnColorChoice(3)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_4"
		area 546 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 4
		action
		"
			mapScreen:OnColorChoice(4)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_5"
		area 624 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 5
		action
		"
			mapScreen:OnColorChoice(5)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_6"
		area 702 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 6
		action
		"
			mapScreen:OnColorChoice(6)
		"
	}
	button
	{
		name "BUTTON_mapNoteColor_7"
		area 166 80 45 42
		bam "FLAG1"
		highlightgroup colorChoice
		sequence 7
		action
		"
			mapScreen:OnColorChoice(7)
		"
	}
}


menu
{
	name "WORLD_MAP"
	align center center
	label
	{
		area 0 0 1024 768
		mosaic GUIMAPWB
	}
	label
	{
		area 211 22 583 44
		text "WORLD_MAP_TITLE"
		text style "title"
	}
	button
	{
		area 51 35 66 58
		bam "MAPBUT"
		action
		"
			worldMapScreen:OnCancelButtonClick()
		"
	}
	map
	{
		area 13 110 1000 649
		worldmap
		action
		"
			worldMapScreen:OnMapMouseDown(eventXCoord,eventYCoord)
		"
		actionDbl
		"
			worldMapScreen:TravelToSelected()
		"
		actionDrag
		"
			worldMapScreen:OnMapMouseMove(eventXCoord,eventYCoord)
		"
	}
	button
	{
		area 808 715 205 44
		enabled "worldMapScreen:IsTravelButtonVisible()"
		bam GUIOSTUM
		text "TRAVEL_BUTTON"
		text style "button"
		clickable lua "worldMapScreen:IsTravelButtonClickable()"
		action "
			worldMapScreen:TravelToSelected()
		"	
	}
}
`

chapterBackground = ""

text_CHAPTERSCROLL = ""
text_CHAPTERSCROLL_timeStart = 0
text_CHAPTERSCROLL_auto = 1
function UpdateChapterScroll(top, height, contentHeight)
	if(text_CHAPTERSCROLL_auto == 0) then
		--defer to default scrolling
		return nil
	end
	local dT = Infinity_GetClockTicks() - text_CHAPTERSCROLL_timeStart
	local newTop = (dT * -0.006) + height
	if(newTop + contentHeight + height < height) then
		return top
	end
	return newTop
end
function setChapterBackground(id)
	chapterBackground = chapterBackgrounds[id]
end
`
menu
{
	name 'CHAPTER'
	align center center
	ignoreEsc
	
	label
	{
		area 0 0 1024 768
		mosaic lua "chapterBackground"
	}
	text
	{
		name "text_CHAPTERSCROLL_item"
		area 96 470 832 224
		text lua "text_CHAPTERSCROLL"
		text style normal
		scrollbar 'GUISCRC'
		scrollbar func 'UpdateChapterScroll'
		scrollbar hide lua 'text_CHAPTERSCROLL_auto == 1'
		action
		"
			text_CHAPTERSCROLL_auto = 0
		"
	}
	button
	{
		area 532 714 234 44
		bam GUIOSTUR
		text "DONE_BUTTON"
		text style "button"
		clickable lua "chapterScreen:IsDoneButtonClickable()"
		action
		"
			chapterScreen:OnDoneButtonClick()
		"
	}
	button
	{
		area 280 714 234 44
		bam GUIOSTUL
		text "REPLAY_BUTTON"
		text style "button"
		clickable lua "chapterScreen:IsReplayButtonClickable()"
		action
		"
			chapterScreen:OnReplayButtonClick()
		"
	}
}
`
epilogueImage = "GUIOSTUR"
`
menu
{
	name 'EPILOGUE'
	align center center
	ignoreEsc
	
	label
	{
		area 0 0 1024 768
		mosaic "NPCCHAP"
	}
	label
	{
		area 106 230 210 330
		bitmap lua "epilogueImage"
	}
	text
	{
		name "text_CHAPTERSCROLL_item"
		area 424 128 540 534
		text lua "text_CHAPTERSCROLL"
		text style normal
		scrollbar 'GUISCRC'
		scrollbar func 'UpdateChapterScroll'
		scrollbar hide lua 'text_CHAPTERSCROLL_auto == 1'
		action
		"
			text_CHAPTERSCROLL_auto = 0
		"
	}
	button
	{
		area 590 708 234 44
		bam GUIOSTUR
		text "DONE_BUTTON"
		text style "button"
		clickable lua "chapterScreen:IsDoneButtonClickable()"
		action
		"
			chapterScreen:OnDoneButtonClick()
		"
	}
	button
	{
		area 252 708 234 44
		bam GUIOSTUL
		text "REPLAY_BUTTON"
		text style "button"
		clickable lua "chapterScreen:IsReplayButtonClickable()"
		action
		"
			chapterScreen:OnReplayButtonClick()
		"
	}
}
menu
{
	name 'CHAPTER_WAITING_FOR_PROVIDER'
	modal
	align center center

	label
	{
		area 0 0 406 418
		mosaic GUIERR
	}
	label --Title
	{
		area 74 82 254 80
		text "WAITING_FOR_OTHER_PLAYERS"
		text style	"label"
	}
}
`
store = {}
storeGroupItemsVar = 0
storeItemsVar = 0
function getStoreSlotHighlight(highlight)
	if(highlight == 0) then 
		return 0
	else
		return 2 
	end
end
function storeSplitStack(count)
	storeScreen:SelectStoreItem(storeItemsVar-1, true);
	storeScreen:SetStoreItemCount(storeItemsVar-1, count);
end
function groupSplitStack(count)
	storeScreen:SelectGroupItem(storeGroupItemsVar-1, true);
	storeScreen:SetGroupItemCount(storeGroupItemsVar-1, count);
end
function checkContainerText(normalStr, containerStr)
	if(storeScreen:IsContainer()) then
		return t(containerStr)
	else
		return t(normalStr)
	end
end
function getStoreItemCount(row)
	local count = store.storeItems[rowNumber].item.count
	if(count ~= 0xFFFF)  then 
		return count
	else
		-- maxword, infinite count.
		return nil
	end
end
`
menu
{
	name 'STORE_BUYSELL'
	align center top
	onOpen "storeScreen:UpdateBuySellPanel()"
	ignoreEsc
	label
	{
		area 0 0 864 598
		mosaic GUISTBSC
	}
	label
	{
		area 48 16 768 44
		text lua "checkContainerText('BUY_SELL_TITLE','CONTAINER_TITLE')"
		text style "title"
	}
	label
	{
		area 266 85 330 27
		text lua "Infinity_FetchString(storeScreen:GetStoreName())"
		text style "label"
	}
	label
	{
		area 717 116 108 30
		enabled "not storeScreen:IsContainer()"
		text lua "game:GetPartyGold()"
		text style "gold"
		align right center
	}
	label
	{
		area 94 499 146 23
		enabled "not storeScreen:IsContainer()"
		text "COST_LABEL"
		text style "label"
		align right center
	}
	label
	{
		area 319 499 108 23
		enabled "not storeScreen:IsContainer()"
		text lua "storeScreen:GetStoreCost()"
		text style "normal"
		align right center
	}
	label
	{
		area 533 499 146 23
		enabled "not storeScreen:IsContainer()"
		text "PRICE_LABEL"
		text style "label"
		align right center
	}
	label
	{
		area 717 499 108 23
		enabled "not storeScreen:IsContainer()"
		text lua "storeScreen:GetGroupCost()"
		text style "normal"
		align right center
	}
	
	label
	{
		area 26 116 349 30
		text lua "checkContainerText('STORE_LABEL',Infinity_FetchString(storeScreen:GetStoreName()))"
		text style "label"
		align left center
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 5 0 64 60
				bam STONSLOT
				frame lua "getStoreSlotHighlight(store.storeItems[rowNumber].highlight)"
				icon lua "store.storeItems[rowNumber].item.icon"
				tint lua "store.storeItems[rowNumber].item.tint"
				usages lua "store.storeItems[rowNumber].amountSelected" --how many selected
				count lua "store.storeItems[rowNumber].item.stackSize" --How many to a stack
				align center center
			}
			label
			{
				area 80 0 250 60
				text lua "store.storeItems[rowNumber].label"
				text style "normal"
				text align left center
			}
			label
			{
				area 310 0 91 60
				enabled "not storeScreen:IsContainer()"
				text lua "store.storeItems[rowNumber].value"
				text style "gold"
			}
			label
			{
				enabled "store.storeItems[rowNumber].valid == 0 and store.storeItems[rowNumber].highlight == 0"
				area 0 0 436 60
				rectangle 1
				rectangle opacity 150
			}
		}
		area 26 146 406 344
		hidehighlight
		rowheight	60
		table		"store.storeItems"
		var			"storeItemsVar"
		scrollbar 'GUISCRC'
		action
		"
			if store.storeItems[storeItemsVar].clickable == 1 then
				if not storeScreen:IsCloseBagButtonClickable() or store.storeItems[storeItemsVar].valid == 1 then
					local highlight = true
					if(store.storeItems[storeItemsVar].highlight == 1) then highlight = false end
					storeScreen:SelectStoreItem( storeItemsVar - 1,  highlight)
				end
			end
		"
		actionalt
		"
			showItemDescription(store.storeItems[storeItemsVar].item, 1)
		"
		actionDbl
		"
			if store.storeItems[storeItemsVar].clickable == 1 then
				if not storeScreen:IsCloseBagButtonClickable() or store.storeItems[storeItemsVar].valid == 1 then
					local maxCount = store.storeItems[storeItemsVar].maxCount
					if(maxCount > 1) then
						popupRequester(maxCount, storeSplitStack, false)
					end
				end
			end
		"
	}
	
	label
	{
		area 467 116 250 30
		text  lua "Infinity_GetSelectedCharacterName()"
		text style "label"
		align left center
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 5 0 64 60
				bam STONSLOT
				frame lua "getStoreSlotHighlight(store.groupItems[rowNumber].highlight)"
				tint lua "store.groupItems[rowNumber].item.tint"
				icon lua "store.groupItems[rowNumber].item.icon"
				count lua "store.groupItems[rowNumber].count"
				usages lua "store.groupItems[rowNumber].item.usages"
				align center center
			}
			label
			{
				area 80 0 200 60
				text lua "store.groupItems[rowNumber].label"
				text style "normal"
				text align left center
			}
			label
			{
				area 300 0 62 60
				enabled "not storeScreen:IsContainer()"
				text lua "store.groupItems[rowNumber].value"
				text style "gold"
			}
			label
			{
				--#21242 We don't grey out bags, even though they're not selectable, because we can open them.
				enabled "store.groupItems[rowNumber].valid == 0  and store.groupItems[rowNumber].item.isBag ~= 1"
				area 0 0 436 60
				rectangle 1
				rectangle opacity 150
			}
		}
		area 462 146 368 344
		enabled "not storeScreen:IsCloseBagButtonClickable()"
		hidehighlight
		rowheight	60
		table		"store.groupItems"
		var			"storeGroupItemsVar"
		scrollbar 'GUISCRC'
		action
		"
			if store.groupItems[storeGroupItemsVar].valid ~= 0 then
				local selected = true
				if(store.groupItems[storeGroupItemsVar].highlight == 1) then selected = false end
				storeScreen:SelectGroupItem( storeGroupItemsVar - 1,  selected)
			end
		"
		actionalt
		"
			showItemDescription(store.groupItems[storeGroupItemsVar].item, 1)
		"
		actionDbl
		"
		if(store.groupItems[storeGroupItemsVar].item.isBag == 1) then
			showItemDescription(store.groupItems[storeGroupItemsVar].item, 1)
			itemDescLeftButtonAction()
		else
			if store.groupItems[storeGroupItemsVar].valid ~= 0 then
				local count = store.groupItems[storeGroupItemsVar].item.count
				local stock = store.groupItems[storeGroupItemsVar].numInStock
				if(count > 1) then
					popupRequester(count, groupSplitStack, true)
				elseif stock > 1 then
					popupRequester(stock, groupSplitStack, true)
				end	
			end
		end
		"
	}

	list
	{
		column 
		{ 
			width 100
			label
			{
				area 5 0 64 60
				bam STONSLOT
				frame lua "getStoreSlotHighlight(store.groupItems[rowNumber].highlight)"
				tint lua "store.groupItems[rowNumber].item.tint"
				icon lua "store.groupItems[rowNumber].item.icon"
				count lua "store.groupItems[rowNumber].item.count"
				usages lua "store.groupItems[rowNumber].count"
				align center center
			}
			label
			{
				area 80 0 200 60
				text lua "store.groupItems[rowNumber].label"
				text style "normal"
				text align left center
			}
			label
			{
				area 300 0 62 60
				enabled "not storeScreen:IsContainer()"
				text lua "store.groupItems[rowNumber].value"
				text style "gold"
			}
			label
			{
				enabled "store.groupItems[rowNumber].valid == 0"
				area 0 0 436 60
				rectangle 1
				rectangle opacity 150
			}
		}
		area 462 146 372 344
		enabled "storeScreen:IsCloseBagButtonClickable()"
		hidehighlight
		rowheight	60
		table		"store.groupItems"
		var			"storeGroupItemsVar"
		scrollbar 'GUISCRC'
		action
		"
			if store.groupItems[storeGroupItemsVar].valid ~= 0 then
				local selected = true
				if(store.groupItems[storeGroupItemsVar].highlight == 1) then selected = false end
				storeScreen:SelectGroupItem( storeGroupItemsVar - 1,  selected)
			end
		"
		actionalt
		"
			showItemDescription(store.groupItems[storeGroupItemsVar].item, 1)
		"
		actionDbl
		"
			if store.groupItems[storeGroupItemsVar].valid ~= 0 then
				local count = store.groupItems[storeGroupItemsVar].item.count
				local stock = store.groupItems[storeGroupItemsVar].numInStock
				if(count > 1) then
					popupRequester(count, groupSplitStack, true)
				elseif stock > 1 then
					popupRequester(stock, groupSplitStack, true)
				end	
			end
		"
	}

	button
	{
		area 118 532 201 43
		bam GUIOSTUM
		text lua "checkContainerText('BUY_BUTTON', 'TO_BACKPACK_BUTTON')"
		text style "button"
		clickable lua "storeScreen:IsBuyItemButtonClickable()"
		action
		"
			storeScreen:OnBuyItemButtonClick()
		"
	}
	button
	{
		area 604 532 201 43
		bam GUIOSTUM
		text lua "checkContainerText('SELL_BUTTON','TO_CONTAINER_BUTTON')"
		text style "button"
		clickable lua "storeScreen:IsSellItemButtonClickable()"
		action
		"
			storeScreen:OnSellItemButtonClick()
		"
	}
	button
	{
		area 360 532 201 43
		enabled "(not storeScreen:IsContainer()) and storeScreen:IsStealEnabled()"
		bam GUIOSTUM
		text "STEAL_BUTTON"
		text style "button"
		clickable lua "storeScreen:IsStealItemButtonClickable()"
		action
		"
			storeScreen:OnStealItemButtonClick()
		"
	}
	button
	{
		area 361 532 200 42
		enabled "storeScreen:IsCloseBagButtonClickable()"
		bam GUIOSTUM
		text "CLOSE_CONTAINER_BUTTON"
		text style "button"
		action
		"
			storeScreen:OnCloseBagButtonClick()
		"
	}
	button
	{
		area 14 496 68 90
		encumbrance
	}

	label
	{
		area 26 146 406 344
		enabled "storeScreen:IsSpriteOrderable() == false"
		rectangle 0
		rectangle opacity 200
		ignoreEvents
	}
 
	label
	{
		area 462 146 372 344
		enabled "storeScreen:IsSpriteOrderable() == false"
		rectangle 0
		rectangle opacity 200
		ignoreEvents
	}
}
`
	identifyItemsVar = 0
`
menu
{
	name 'STORE_IDENTIFY'
	align center top
	onOpen
	"
		storeScreen:UpdateIdentifyPanel()
		store.identifyText = ''
		
	"
	ignoreEsc
	
	label
	{
		area 0 0 864 598
		mosaic GUISTIDB
	}
	label
	{
		area 48 6 768 52
		text "IDENTIFY_TITLE"
		text style "title"
	}
	label
	{
		area 274 62 314 24
		text lua "Infinity_FetchString(storeScreen:GetStoreName())"
		text style "label"
	}
	label
	{
		area 274 90 314 22
		text lua "game:GetPartyGold()"
		text style "gold"
	}
	label
	{
		area 68 126 144 32
		text "COST_LABEL"
		text style "label"
		text align left center
	}
	label
	{
		area 282 126 90 36
		text lua "storeScreen:GetIdentifyCost()"
		text style "gold"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 5 0 64 60
				bam STONSLOT
				frame lua "getStoreSlotHighlight(store.identifyItems[rowNumber].highlight)"
				icon lua "store.identifyItems[rowNumber].item.icon"
				tint lua "store.identifyItems[rowNumber].item.tint"
				align center center
			}
			label
			{
				area 80 0 204 60
				text lua "store.identifyItems[rowNumber].label"
				text style "normal"
				text align left center
			}
			label
			{
				enabled "store.identifyItems[rowNumber].valid == 0"
				area 0 0 308 60
				rectangle 1
				rectangle opacity 150
			}
		}
		area 68 166 304 384
		hidehighlight
		rowheight	60
		table		"store.identifyItems"
		var			"identifyItemsVar"
		scrollbar 'GUISCRC'
		action
		"
			local highlight = true
			if(store.identifyItems[identifyItemsVar].highlight == 1) then highlight = false end
			if(highlight == true and store.identifyItems[identifyItemsVar].valid == 0) then return end
			storeScreen:SelectIdentifyItem( identifyItemsVar - 1,  highlight)
		"
	}
	button
	{
		area 118 554 204 44	
		bam GUIOSTUM
		text "IDENTIFY_BUTTON"
		text style "button"
		clickable lua "storeScreen:IsIdentifyItemButtonClickable()"
		action
		"
			storeScreen:OnIdentifyItemButtonClick()
		"
	}
	text
	{
		area 461 150 365 412
		text lua "store.identifyText"
		text style "normal_parchment"
		scrollbar 'GUISCRC'
	}
}
`
function getDonationFrame()
	if(store.hasDonated ~= nil and store.hasDonated == 1) then
		return 1
	else
		return 0
	end
end
storeDonateAmountEdit = 0 --no longer used in ui, but the engine needs it.
function changeDonationAmount(amount)
	if (amt == nil) then
		amt = 0
	end
	amt = amt + amount

	if (amt > 0) then
		storeDonateAmountEdit = tostring(amt)
	else
		storeDonateAmountEdit = '0'
	end
end	
`
menu
{
	name 'STORE_DONATE'
	align center top
	ignoreEsc
	onOpen 
	"
		storeScreen:UpdateDonatePanel()
		store.donateText = ''
	"

	label
	{
		area 0 0 864 598
		mosaic GUISTDOB
	}
	label
	{
		area 48 6 768 44
		text "DONATE_TITLE"
		text style "title"
	}
	label
	{
		area 277 68 310 26
		text lua "Infinity_FetchString(storeScreen:GetStoreName())"
		text style "label"
	}
	label
	{
		area 73 151 311 267
		bam "DONATE"
		frame lua "getDonationFrame()"
	}
	label
	{
		area 51 431 346 38
		text "ENTER_DONATION_LABEL"
		text style "label"
	}
	edit
	{
		name		"storeDonateAmountEditArea"
		area		119 477 122 48
		var			storeDonateAmountEdit
		text style	"edit"
		text align left center
		maxlines	1
		action
		"
			-- only permit numbers as letters.
			if(tonumber(letter_pressed) ~= nil or not letter_pressed) then
				return 1
			else
				return 0
			end
		"
	}
	button
	{
		bam GUIOSW
		area 244 481 44 44
		sequence 0
		action
		"
			changeDonationAmount(1)
		"
		actionHold
		"
			changeDonationAmount(1)
		"
	}
	button
	{
		bam GUIOSW
		area 288 481 44 44
		sequence 1
		clickable lua "tonumber(storeDonateAmountEdit) > 0"
		action
		"
				changeDonationAmount(-1)
		"
		actionHold
		"
				changeDonationAmount(-1)
		"
	}
	button
	{
		area 119 537 204 44
		bam GUIOSTUM
		text "DONATE_BUTTON"
		text style "button"
		clickable lua "storeScreen:IsDonateButtonClickable()"
		action
		"
			storeScreen:OnDonateButtonClick()
		"
	}
	label
	{
		area 274 103 313 31
		text lua "game:GetPartyGold()"
		text style "gold"
	}
	text
	{
		area 473 182 320 364
		text lua "store.donateText"
		text style "normal_parchment"
		scrollbar 'GUISCRC'
	}
}
`
	function storeRest()
		storeScreen:RestParty()
	end
`
menu
{
	name 'STORE_ROOMS'
	align center top
	onOpen 
	"
		storeScreen:SetRoomType(0)
		storeScreen:UpdateRentRoomPanel()
	"
	ignoreEsc
	
	label
	{
		area 0 0 864 598
		mosaic GUISTROB
	}
	label
	{
		area 48 6 768 44
		text "ROOMS_TITLE"
		text style "title"
	}
	label
	{
		area 254 58 360 30
		text lua "Infinity_FetchString(storeScreen:GetStoreName())"
		text style "label"
	}
	label
	{
		area 254 84 360 30
		text lua "game:GetPartyGold()"
		text style "gold"
	}
	
	button
	{
		area 31 128 245 161
		bam "INNROOMS"
		sequence 0
		clickable lua "storeScreen:IsRoomTypeClickable(1)"
		action
		"
			storeScreen:SetRoomType(1)
			selectedRoom = Infinity_FindUIItemByName('BUTTON_room_peasant')
		"
	}
	button
	{
		name "BUTTON_room_peasant"
		area 31 304 202 44
		bam GUIOSTUM
		text "PEASANT_BUTTON"
		text style "button"
		glow lua "storeScreen:GetRoomType() == 1"
		clickable lua "storeScreen:IsRoomTypeClickable(1)"
		action
		"
			storeScreen:SetRoomType(1)
		"
	}
	
	button
	{
		area 385 128 245 161
		bam "INNROOMS"
		sequence 1
		clickable lua "storeScreen:IsRoomTypeClickable(2)"
		action
		"
			storeScreen:SetRoomType(2)
			selectedRoom = Infinity_FindUIItemByName('BUTTON_room_merchant')
		"
	}
	button
	{
		name "BUTTON_room_merchant"
		area 385 304 202 44
		bam GUIOSTUM
		text "MERCHANT_BUTTON"
		text style "button"
		glow lua "storeScreen:GetRoomType() == 2"
		clickable lua "storeScreen:IsRoomTypeClickable(2)"
		action
		"
			storeScreen:SetRoomType(2)
		"
	}
	
	button
	{
		area 31 367 245 161
		bam "INNROOMS"
		sequence 2
		clickable lua "storeScreen:IsRoomTypeClickable(3)"
		frame 0
		action
		"
			storeScreen:SetRoomType(3)
			selectedRoom = Infinity_FindUIItemByName('BUTTON_room_noble')
		"
	}
	button
	{
		name "BUTTON_room_noble"
		area 31 540 202 44
		bam GUIOSTUM
		text "NOBLE_BUTTON"
		text style "button"
		glow lua "storeScreen:GetRoomType() == 3"
		clickable lua "storeScreen:IsRoomTypeClickable(3)"
		action
		"
			storeScreen:SetRoomType(3)
		"
	}
	
	button
	{
		area 385 367 245 161
		bam "INNROOMS"
		sequence 3
		clickable lua "storeScreen:IsRoomTypeClickable(4)"
		action
		"
			storeScreen:SetRoomType(4)
			selectedRoom = Infinity_FindUIItemByName('BUTTON_room_royal')
		"
	}
	button
	{
		name "BUTTON_room_royal"
		area 385 540 202 44
		bam GUIOSTUM
		text "ROYAL_BUTTON"
		text style "button"
		glow lua "storeScreen:GetRoomType() == 4"
		clickable lua "storeScreen:IsRoomTypeClickable(4)"
		action
		"
			storeScreen:SetRoomType(4)
		"
	}
	label
	{
		area 654 464 70 40
		text "COST_LABEL"
		text style "label"
	}
	text
	{
		area 662 137 160 298
		text lua "store.roomText"
		text style "normal"
	}
	label
	{
		area 727 464 120 40
		text lua "storeScreen:GetRoomCost()"
		text style "gold"
	}
	button
	{
		area 643 516 204 48
		bam GUIOSTUM
		text "RENT_BUTTON"
		text style "button"
		action
		"
			storeScreen:OnRentRoomButtonClick()
		"
	}
}
menu
{
	name 'STORE_HEALING'
	align center top
	onOpen "storeScreen:UpdateBuySpellPanel()"
	ignoreEsc
	label
	{
		area 0 0 864 598
		mosaic GUISTIDB
	}
	label
	{
		area 48 6 768 52
		text "HEALING_TITLE"
		text style "title"
	}
	label
	{
		area 274 62 314 24
		text lua "Infinity_FetchString(storeScreen:GetStoreName())"
		text style "label"
	}
	label
	{
		area 274 90 314 22
		text lua "game:GetPartyGold()"
		text style "gold"
	}
	label
	{
		area 68 126 144 32
		text "COST_LABEL"
		text style "label"
		align left center
	}
	label
	{
		area 282 126 90 32
		text lua "storeScreen:GetSpellCost()"
		text style "gold"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 5 0 64 60
				bam STONSLOT
				frame lua "getStoreSlotHighlight(store.healingSpells[rowNumber].highlight)"
				icon lua "store.healingSpells[rowNumber].icon"
				tint lua "store.healingSpells[rowNumber].tint"
				align center center
			}
			label
			{
				area 80 0 150 60
				text lua "Infinity_FetchString(store.healingSpells[rowNumber].name)"
				text style "normal"
				text align left center
			}
			label
			{
				area 230 0 54 60
				text style "gold"
				text align center center
				text lua "store.healingSpells[rowNumber].value"
			}
			label
			{
				enabled "store.healingSpells[rowNumber].valid == 0"
				area 0 0 308 60
				rectangle 1
				rectangle opacity 150
			}
		}
		area 64 164 308 386
		hidehighlight
		rowheight	60
		table		"store.healingSpells"
		var			"healingSpellsVar"
		scrollbar 'GUISCRC'
		action
		"
			local highlight = true
			if(store.healingSpells[healingSpellsVar].highlight == 1) then highlight = false end
			if(highlight == true and store.healingSpells[healingSpellsVar].valid == 0) then return end
			storeScreen:SelectSpellItem( healingSpellsVar - 1,  highlight)
		"
		actionAlt
		"
			local spell = store.healingSpells[healingSpellsVar]
			popupDetails(16189, spell.name, spell.description,spell.icon)
		"
	}
	button
	{
		area 120 554 200 44
		bam GUIOSTUM
		text "BUY_BUTTON"
		text style "button"
		action
		"
			storeScreen:OnBuySpellButtonClick()
		"
	}
	text
	{
		area 461 150 350 412
		text lua "store.spellText"
		text style "normal_parchment"
		scrollbar 'GUISCRC'
	}
}

menu
{
	name 'STORE_DRINKS'
	align center top
	ignoreEsc
	onOpen 
	"
		storeScreen:UpdateBuyDrinksPanel()
		store.drinkText = ''
	"
	
	label
	{
		area 0 0 864 598
		mosaic GUISTIDB
	}
	label
	{
		area 48 6 768 44
		text "DRINKS_TITLE"
		text style "title"
	}
	label
	{
		area 277 64 310 24
		text lua "Infinity_FetchString(storeScreen:GetStoreName())"
		text style "label"
	}
	label
	{
		area 272 88 315 28
		text lua "game:GetPartyGold()"
		text style "gold"
	}
	label
	{
		area 64 127 202 31
		text "DRINK_LABEL"
		text style "label"
	}
	label
	{
		area 266 127 111 31
		text "COST_LABEL"
		text style "label"
		text align center center
	}
	label
	{
		area 64 158 308 396
		rectangle 1
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 5 0 200 60
				text lua "store.drinks[rowNumber].name"
				text style "normal"
				text align left center
			}
			label
			{
				area 210 0 64 60
				text lua "store.drinks[rowNumber].value"
				text style "gold"
				text align center center
			}
			label
			{
				enabled "store.drinks[rowNumber].valid == 0"
				area 0 0 308 60
				rectangle 1
				rectangle opacity 150
			}
		}
		area 64 155 308 399
		rowheight	60
		table		"store.drinks"
		var			"storeDrinksVar"
		scrollbar 'GUISCRC'
	}
	button
	{
		area 118 554 204 48
		bam GUIOSTUM
		text "BUY_BUTTON"
		text style "button"
		clickable lua "storeDrinksVar ~= nil and storeDrinksVar ~= 0"
		action
		"
			storeScreen:OnBuyDrinkButtonClick(storeDrinksVar - 1)
		"
	}
	label
	{
		area 489 158 127 93
		bam lua "store.qualityIcon"
	}
	label
	{
		area 616 150 155 93
		text "RUMORS_LABEL"
		text style "label_parchment"
	}
	text
	{
		area 489 251 310 296
		text lua "store.drinkText"
		text style "normal_parchment"
		scrollbar 'GUISCRC'
	}
}
`
	storePanelButtonHighlightGroup = nil
	function setStoreMainPanel(buttonId)
		local oldMenu  = storeScreen:GetMenuName(storeCurMenuId)
		Infinity_PopMenu(oldMenu)
		storeCurMenuId = storeScreen:GetPanelButtonPanelId(buttonId)
		Infinity_PushMenu(storeScreen:GetMenuName(storeCurMenuId))
	end
	function getBuySellTooltip()
		if(storeScreen:IsContainer()) then
			return t('TRANSFER_ITEMS_TOOLTIP')
		else
			return Infinity_FetchString(storeScreen:GetPanelButtonToolTip(0))
		end
	end
`
menu
{
	name 'STORE_CHOOSER'
	align center bottom
	onOpen
	"
		local menuName = storeScreen:GetMenuName(storeCurMenuId)
		Infinity_PushMenu(menuName)
		pushSidebars()
		local buttonId = storeScreen:GetPanelButtonId(storeCurMenuId)
		storePanelButtonHighlightGroup = Infinity_FindUIItemByName('BUTTON_storechooser_' .. buttonId)
	"
	onClose 
	"
		local menuName = storeScreen:GetMenuName(storeCurMenuId)
		Infinity_PopMenu(menuName)
		popSidebars()
	"
	ignoreEsc
	
	label
	{
		area 0 0 864 112
		mosaic GUISTBBB
	}
	label
	{
		area 22 18 80 70
		bam lua "store.icon"
	}
	button
	{
		area 638 60 204 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		action
		"
			storeScreen:OnMainDoneButtonClick()
		"
	}
	button
	{
		name 'BUTTON_storechooser_0'
		area 110 18 62 64
		enabled "storeScreen:GetPanelButtonEnabled(0)"
		bam GUISTBBC
		highlightgroup storePanelButtonHighlightGroup
		sequence lua "storeScreen:GetPanelButtonSequence(0)"
		tooltip lua "getBuySellTooltip()"
		action
		"
			setStoreMainPanel(0)
		"
	}
	button
	{
		name 'BUTTON_storechooser_1'
		area 182 18 62 64
		enabled "storeScreen:GetPanelButtonEnabled(1)"
		bam GUISTBBC
		highlightgroup storePanelButtonHighlightGroup
		sequence lua "storeScreen:GetPanelButtonSequence(1)"
		tooltip lua "Infinity_FetchString(storeScreen:GetPanelButtonToolTip(1))"
		action
		"
			setStoreMainPanel(1)
		"
	}
	button
	{
		name 'BUTTON_storechooser_2'
		area 254 18 62 64
		enabled "storeScreen:GetPanelButtonEnabled(2)"
		bam GUISTBBC
		highlightgroup storePanelButtonHighlightGroup
		sequence lua "storeScreen:GetPanelButtonSequence(2)"
		tooltip lua "Infinity_FetchString(storeScreen:GetPanelButtonToolTip(2))"
		action
		"
			setStoreMainPanel(2)
		"
	}
	button
	{
		name 'BUTTON_storechooser_3'
		area 326 18 62 64
		enabled "storeScreen:GetPanelButtonEnabled(3)"
		bam GUISTBBC
		highlightgroup storePanelButtonHighlightGroup
		sequence lua "storeScreen:GetPanelButtonSequence(3)"
		tooltip lua "Infinity_FetchString(storeScreen:GetPanelButtonToolTip(3))"
		action
		"
			setStoreMainPanel(3)
		"
	}
}
`
	function worldDeathLoadClickable()
		if(e:IsMultiplayer() and not e:IsHosting()) then
			return false
		end
		return not worldScreen:GetHardPaused()
	end
	function worldDeathQuitClickable()
		return not worldScreen:GetHardPaused()
	end
	function worldDeathText()
		if(e:IsMultiplayer()) then
			if(e:IsHosting()) then
				return Infinity_FetchString(19377)
			else
				return Infinity_FetchString(11331)
			end
		else
			if(worldDeathStr == nil) then
				return Infinity_FetchString(16498)
			else
				return Infinity_FetchString(worldDeathStr)
			end
		end
	end
	function worldDeathQuitText()
		if(e:IsMultiplayer()) then
			return t('LOGOUT_BUTTON')
		else
			return t('QUIT_BUTTON')
		end
	end
	groundItemsButtonToggle = 0
	highlightButtonToggle = 0
	worldChatEdit = ""
`
menu
{
	name "WORLD_DEATH"
	align center center
	ignoreEsc
	modal
	label
	{
		area 0 0 657 234
		mosaic GUIERR6
	}
	label
	{
		area 29 21 609 126
		text lua "worldDeathText()"
		text style	"label"
		text align center center
	}
	button
	{
		area 88 170 234 44
		bam GUIOSTUL
		text "LOAD_BUTTON"
		text style	"button"
		clickable lua "worldDeathLoadClickable()"
		action 
		"
			Infinity_PopMenu()
			worldScreen:OnDeathLoad()
		"
	}
	button
	{
		area 364 170 234 44
		bam GUIOSTUR
		text style	"button"
		text lua "worldDeathQuitText()"
		clickable lua "worldDeathQuitClickable()"
		action 
		"
			Infinity_PopMenu()
			worldScreen:OnDeathQuit()
		"
	}
}
`
	actionBarTooltip = {}
`
menu
{
	name "WORLD_ACTIONBAR"
	align center bottom
	onOpen 
	"
		toolbarTop = 50
		Infinity_PushMenu('WORLD_MESSAGES')
		if(groundItemsButtonToggle == 1) then
			worldScreen:StartGroundItems()
		end
		worldScreen:SetHighlightEnabled(highlightButtonToggle == 1)
	"
	onClose 
	"
		Infinity_PopMenu('WORLD_QUICKLOOT');
		Infinity_PopMenu('WORLD_MESSAGES');
	"
	ignoreEsc
	label
	{
		area 0 0 746 57
		mosaic GUWBTP10
	}
	button
	{
		area 21 12 32 32
		bam ROUNDBUT
		tooltip lua "Infinity_FetchString(99897)"
		toggle groundItemsButtonToggle
		action
		"
			if(groundItemsButtonToggle == 1) then
				worldScreen:StartGroundItems()
			else
				worldScreen:StopGroundItems()
			end
		"
		actionAlt
		"
			if(groundItemsButtonToggle == 1) then
				worldScreen:StartGroundItems()
			else
				worldScreen:StopGroundItems()
			end
		"
	}
	button
	{
		area 68 1 52 52
		actionBar 0
		enabled "buttonArray:GetButtonEnabled(0)"
		tooltip lua "actionBarTooltip[0]"
		action "buttonArray:OnLButtonPressed(0)"
		actionAlt "buttonArray:OnRButtonPressed(0)"
	}
	button
	{
		area 122 1 52 52
		actionBar 1
		enabled "buttonArray:GetButtonEnabled(1)"
		tooltip lua "actionBarTooltip[1]"
		action "buttonArray:OnLButtonPressed(1)"
		actionAlt "buttonArray:OnRButtonPressed(1)"
	}
	button
	{
		area 177 1 52 52
		actionBar 2
		enabled "buttonArray:GetButtonEnabled(2)"
		tooltip lua "actionBarTooltip[2]"
		action "buttonArray:OnLButtonPressed(2)"
		actionAlt "buttonArray:OnRButtonPressed(2)"
	}
	button
	{
		area 231 1 52 52
		actionBar 3
		enabled "buttonArray:GetButtonEnabled(3)"
		tooltip lua "actionBarTooltip[3]"
		action "buttonArray:OnLButtonPressed(3)"
		actionAlt "buttonArray:OnRButtonPressed(3)"
	}
	button
	{
		area 299 1 52 52
		actionBar 4
		enabled "buttonArray:GetButtonEnabled(4)"
		tooltip lua "actionBarTooltip[4]"
		action "buttonArray:OnLButtonPressed(4)"
		actionAlt "buttonArray:OnRButtonPressed(4)"
	}
	button
	{
		area 353 1 52 52
		actionBar 5
		enabled "buttonArray:GetButtonEnabled(5)"
		tooltip lua "actionBarTooltip[5]"
		action "buttonArray:OnLButtonPressed(5)"
		actionAlt "buttonArray:OnRButtonPressed(5)"
	}
	button
	{
		area 407 1 52 52
		actionBar 6
		enabled "buttonArray:GetButtonEnabled(6)"
		tooltip lua "actionBarTooltip[6]"
		action "buttonArray:OnLButtonPressed(6)"
		actionAlt "buttonArray:OnRButtonPressed(6)"
	}
	button
	{
		area 461 1 52 52
		actionBar 7
		enabled "buttonArray:GetButtonEnabled(7)"
		tooltip lua "actionBarTooltip[7]"
		action "buttonArray:OnLButtonPressed(7)"
		actionAlt "buttonArray:OnRButtonPressed(7)"
	}
	
	button
	{
		area 528 1 52 52
		actionBar 8
		enabled "buttonArray:GetButtonEnabled(8)"
		tooltip lua "actionBarTooltip[8]"
		action "buttonArray:OnLButtonPressed(8)"
		actionAlt "buttonArray:OnRButtonPressed(8)"
	}
	button
	{
		area 582 1 52 52
		actionBar 9
		enabled "buttonArray:GetButtonEnabled(9)"
		tooltip lua "actionBarTooltip[9]"
		action "buttonArray:OnLButtonPressed(9)"
		actionAlt "buttonArray:OnRButtonPressed(9)"
	}
	button
	{
		area 636 1 52 52
		actionBar 10
		enabled "buttonArray:GetButtonEnabled(10)"
		tooltip lua "actionBarTooltip[10]"
		action "buttonArray:OnLButtonPressed(10)"
		actionAlt "buttonArray:OnRButtonPressed(10)"
	}
	button
	{
		area 689 1 52 52
		actionBar 11
		enabled "buttonArray:GetButtonEnabled(11)"
		tooltip lua "actionBarTooltip[11]"
		action "buttonArray:OnLButtonPressed(11)"
		actionAlt "buttonArray:OnRButtonPressed(11)"
	}
}
`
	loot = 
	{
		containerItems = {},
		groupItems = {},
		groundItems = {}
	}
	function getContainerItemProperty(index, property)
		local idxScrolled = index + worldScreen:GetTopContainerItem()
		if(loot.containerItems[idxScrolled] == nil or loot.containerItems[idxScrolled].item == nil) then
			return nil
		end
		return loot.containerItems[idxScrolled].item[property]
	end
	function getGroupItemProperty(index, property)
		local idxScrolled = index + worldScreen:GetTopGroupItem()
		if(loot.groupItems[idxScrolled] == nil or loot.groupItems[idxScrolled].item == nil) then
			return nil
		end
		return loot.groupItems[idxScrolled].item[property]
	end
	function scrollContainerItems()
		if scrollDirection > 0 then
			if worldScreen:ContainerScrollEnabled(-1) then
				worldScreen:OnContainerScroll(-1)
			end
		elseif scrollDirection < 0 then
			if worldScreen:ContainerScrollEnabled(1) then
				worldScreen:OnContainerScroll(1)
			end
		end
	end
	function scrollGroupItems()
		if scrollDirection > 0 then
			if worldScreen:GroupScrollEnabled(-1) then
				worldScreen:OnGroupScroll(-1)
			end
		elseif scrollDirection < 0 then
			if worldScreen:GroupScrollEnabled(1) then
				worldScreen:OnGroupScroll(1)
			end
		end
	end
	function showContainerItemDescription(index)
		local idxScrolled = index + worldScreen:GetTopContainerItem()
		if(loot.containerItems[idxScrolled] == nil or loot.containerItems[idxScrolled].item == nil) then
			return nil
		end
		Infinity_GetContainerItemDescription(idxScrolled)
		showItemDescription(loot.containerItems[idxScrolled].item, 2)
	end
	function showGroupItemDescription(index)
		local idxScrolled = index + worldScreen:GetTopGroupItem()
		if(loot.groupItems[idxScrolled] == nil or loot.groupItems[idxScrolled].item == nil) then
			return nil
		end
		Infinity_GetGroupItemDescription(idxScrolled)
		showItemDescription(loot.groupItems[idxScrolled].item, 2)
	end
`
menu
{
	name "WORLD_CONTAINER"
	align center bottom
	offset -24 0
	ignoreesc
	label
	{
		area 0 0 653 130
		mosaic gmpwmsg0
	}
	label
	{
		area 16 10 83 100
		bam lua "loot.containerIcon"
	}
	button
	{
		area 104 2 209 116
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 108 8 52 52
		bam STONSLOT
		tooltip lua	"getContainerItemProperty(0,'name')"
		tint lua	"getContainerItemProperty(0,'tint')"
		icon lua	"getContainerItemProperty(0,'icon')"
		count lua	"getContainerItemProperty(0,'count')"
		usages lua	"getContainerItemProperty(0,'usages')"
		action		"worldScreen:OnContainerButtonClick(0)"
		actionAlt	"showContainerItemDescription(0)"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 162 8 52 52
		bam STONSLOT
		tooltip lua	"getContainerItemProperty(1,'name')"
		tint lua	"getContainerItemProperty(1,'tint')"
		icon lua	"getContainerItemProperty(1,'icon')"
		count lua	"getContainerItemProperty(1,'count')"
		usages lua	"getContainerItemProperty(1,'usages')"
		action		"worldScreen:OnContainerButtonClick(1)"
		actionAlt	"showContainerItemDescription(1)"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 216 8 52 52
		bam STONSLOT
		tooltip lua	"getContainerItemProperty(2,'name')"
		tint lua	"getContainerItemProperty(2,'tint')"
		icon lua	"getContainerItemProperty(2,'icon')"
		count lua	"getContainerItemProperty(2,'count')"
		usages lua	"getContainerItemProperty(2,'usages')"
		action		"worldScreen:OnContainerButtonClick(2)"
		actionAlt	"showContainerItemDescription(2)"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 108 62 52 52
		bam STONSLOT
		tooltip lua	"getContainerItemProperty(3,'name')"
		tint lua	"getContainerItemProperty(3,'tint')"
		icon lua	"getContainerItemProperty(3,'icon')"
		count lua	"getContainerItemProperty(3,'count')"
		usages lua	"getContainerItemProperty(3,'usages')"
		action		"worldScreen:OnContainerButtonClick(3)"
		actionAlt	"showContainerItemDescription(3)"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 162 62 52 52
		bam STONSLOT
		tooltip lua	"getContainerItemProperty(4,'name')"
		tint lua	"getContainerItemProperty(4,'tint')"
		icon lua	"getContainerItemProperty(4,'icon')"
		count lua	"getContainerItemProperty(4,'count')"
		usages lua	"getContainerItemProperty(4,'usages')"
		action		"worldScreen:OnContainerButtonClick(4)"
		actionAlt	"showContainerItemDescription(4)"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 216 62 52 52
		bam STONSLOT
		tooltip lua	"getContainerItemProperty(5,'name')"
		tint lua	"getContainerItemProperty(5,'tint')"
		icon lua	"getContainerItemProperty(5,'icon')"
		count lua	"getContainerItemProperty(5,'count')"
		usages lua	"getContainerItemProperty(5,'usages')"
		action		"worldScreen:OnContainerButtonClick(5)"
		actionAlt	"showContainerItemDescription(5)"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 268 8 44 44
		enabled "worldScreen:ContainerScrollEnabled(-1)"
		bam guisv10
		sequence 0
		action
		"
			worldScreen:OnContainerScroll(-1)
		"
		actionScroll "scrollContainerItems()"
	}
	button
	{
		area 268 70 44 44
		enabled "worldScreen:ContainerScrollEnabled(1)"
		bam guisv10
		sequence 1
		action
		"
			worldScreen:OnContainerScroll(1)
		"
		actionScroll "scrollContainerItems()"
	}
	label
	{
		area 313 12 68 100
		encumbrance
	}
	button
	{
		area 406 2 162 116
		actionScroll "scrollGroupItems()"
	}
	button
	{
		area 411 8 52 52
		bam STONSLOT
		tooltip lua	"getGroupItemProperty(0,'name')"
		tint lua	"getGroupItemProperty(0,'tint')"
		icon lua	"getGroupItemProperty(0,'icon')"
		count lua	"getGroupItemProperty(0,'count')"
		usages lua	"getGroupItemProperty(0,'usages')"
		action		"worldScreen:OnContainerButtonClick(10)"
		actionAlt	"showGroupItemDescription(0)"
		actionScroll "scrollGroupItems()"
	}
	button
	{
		area 465 8 52 52
		bam STONSLOT
		tooltip lua	"getGroupItemProperty(1,'name')"
		tint lua	"getGroupItemProperty(1,'tint')"
		icon lua	"getGroupItemProperty(1,'icon')"
		count lua	"getGroupItemProperty(1,'count')"
		usages lua	"getGroupItemProperty(1,'usages')"
		action		"worldScreen:OnContainerButtonClick(11)"
		actionAlt	"showGroupItemDescription(1)"
		actionScroll "scrollGroupItems()"
	}
	button
	{
		area 411 62 52 52
		bam STONSLOT
		tooltip lua	"getGroupItemProperty(2,'name')"
		tint lua	"getGroupItemProperty(2,'tint')"
		icon lua	"getGroupItemProperty(2,'icon')"
		count lua	"getGroupItemProperty(2,'count')"
		usages lua	"getGroupItemProperty(2,'usages')"
		action		"worldScreen:OnContainerButtonClick(12)"
		actionAlt	"showGroupItemDescription(2)"
		actionScroll "scrollGroupItems()"
	}
	button
	{
		area 465 62 52 52
		bam STONSLOT
		tooltip lua	"getGroupItemProperty(3,'name')"
		tint lua	"getGroupItemProperty(3,'tint')"
		icon lua	"getGroupItemProperty(3,'icon')"
		count lua	"getGroupItemProperty(3,'count')"
		usages lua	"getGroupItemProperty(3,'usages')"
		action		"worldScreen:OnContainerButtonClick(13)"
		actionAlt	"showGroupItemDescription(3)"
		actionScroll "scrollGroupItems()"
	}
	button
	{
		area 517 8 44 44
		enabled "worldScreen:GroupScrollEnabled(-1)"
		bam guisv10
		sequence 0
		action
		"
			worldScreen:OnGroupScroll(-1)
		"
		actionScroll "scrollGroupItems()"
	}
	button
	{
		area 517 70 44 44
		enabled "worldScreen:GroupScrollEnabled(1)"
		bam guisv10
		sequence 1
		action
		"
			worldScreen:OnGroupScroll(1)
		"
		actionScroll "scrollGroupItems()"
	}
	label
	{
		area 568 20 78 50
		bam GUIGOLD
	}
	label
	{
		area 575 76 71 28
		text lua "game:GetPartyGold()"
		text style "gold"
	}
	button
	{
		area 40 82 32 32
		bam "ROUNDBUT"
		scaleToClip
		action
		"
			worldScreen:TakeAllFromContainer()
		"
	}
}
`
	function getSlotContainerId(index)
		local idxScrolled = index + worldScreen:GetTopGroundItem()
		if(loot.groundItems[idxScrolled] == nil) then
			return nil
		end
		return loot.groundItems[idxScrolled].containerId
	end
	function getGroundItemProperty(index, property)
		local idxScrolled = index + worldScreen:GetTopGroundItem()
		if(loot.groundItems[idxScrolled] == nil or loot.groundItems[idxScrolled].item == nil) then
			return nil
		end
		return loot.groundItems[idxScrolled].item[property]
	end
	
	function groundItemClick(slotId)
		local slot = loot.groundItems[slotId + worldScreen:GetTopGroundItem()]
			if(slot and slot.item) then
				worldScreen:OnGroundButtonClick(slot.slotId, slot.containerId, slot.item.res)
		end
	end
	
	function showGroundItemDescription(slotId)
		local slot = loot.groundItems[slotId + worldScreen:GetTopGroundItem()]
			if(slot and slot.item) then
				Infinity_GetGroundItemDescription(slotId + worldScreen:GetTopGroundItem(), slot.slotId, slot.containerId)
				showItemDescription(slot.item, 2)
		end
	end
`
menu
{
	name 'WORLD_QUICKLOOT'
	align center bottom
	ignoreEsc
	onOpen
	"
		Infinity_SetOffset('WORLD_QUICKLOOT',0, -toolbarTop)
	"
	button
	{
		area 2 4 40 57
		bam GUIBTACT
		frame 44
		enabled "worldScreen:GroundScrollEnabled(-1) or worldScreen:GroundScrollEnabled(1)"
		action
		"
			worldScreen:OnGroundScroll(-1)
		"
	}
	button
	{
		area 610 4 40 57
		bam GUIBTACT
		frame 42
		enabled "worldScreen:GroundScrollEnabled(-1) or worldScreen:GroundScrollEnabled(1)"
		action
		"
			worldScreen:OnGroundScroll(1)
		"
	}
	button
	{
		area 46 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(0,'name')"
		tint lua	"getGroundItemProperty(0,'tint')"
		icon lua	"getGroundItemProperty(0,'icon')"
		count lua	"getGroundItemProperty(0,'count')"
		usages lua	"getGroundItemProperty(0,'usages')"
		action "groundItemClick(0)"
		actionAlt "showGroundItemDescription(0)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(0,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 102 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(1,'name')"
		tint lua	"getGroundItemProperty(1,'tint')"
		icon lua	"getGroundItemProperty(1,'icon')"
		count lua	"getGroundItemProperty(1,'count')"
		usages lua	"getGroundItemProperty(1,'usages')"
		action "groundItemClick(1)"
		actionAlt "showGroundItemDescription(1)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(1,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 158 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(2,'name')"
		tint lua	"getGroundItemProperty(2,'tint')"
		icon lua	"getGroundItemProperty(2,'icon')"
		count lua	"getGroundItemProperty(2,'count')"
		usages lua	"getGroundItemProperty(2,'usages')"
		action "groundItemClick(2)"
		actionAlt "showGroundItemDescription(2)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(2,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 214 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(3,'name')"
		tint lua	"getGroundItemProperty(3,'tint')"
		icon lua	"getGroundItemProperty(3,'icon')"
		count lua	"getGroundItemProperty(3,'count')"
		usages lua	"getGroundItemProperty(3,'usages')"
		action "groundItemClick(3)"
		actionAlt "showGroundItemDescription(3)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(3,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 270 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(4,'name')"
		tint lua	"getGroundItemProperty(4,'tint')"
		icon lua	"getGroundItemProperty(4,'icon')"
		count lua	"getGroundItemProperty(4,'count')"
		usages lua	"getGroundItemProperty(4,'usages')"
		action "groundItemClick(4)"
		actionAlt "showGroundItemDescription(4)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(4,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 326 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(5,'name')"
		tint lua	"getGroundItemProperty(5,'tint')"
		icon lua	"getGroundItemProperty(5,'icon')"
		count lua	"getGroundItemProperty(5,'count')"
		usages lua	"getGroundItemProperty(5,'usages')"
		action "groundItemClick(5)"
		actionAlt "showGroundItemDescription(5)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(5,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 383 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(6,'name')"
		tint lua	"getGroundItemProperty(6,'tint')"
		icon lua	"getGroundItemProperty(6,'icon')"
		count lua	"getGroundItemProperty(6,'count')"
		usages lua	"getGroundItemProperty(6,'usages')"
		action "groundItemClick(6)"
		actionAlt "showGroundItemDescription(6)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(6,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 439 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(7,'name')"
		tint lua	"getGroundItemProperty(7,'tint')"
		icon lua	"getGroundItemProperty(7,'icon')"
		count lua	"getGroundItemProperty(7,'count')"
		usages lua	"getGroundItemProperty(7,'usages')"
		action "groundItemClick(7)"
		actionAlt "showGroundItemDescription(7)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(7,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 495 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(8,'name')"
		tint lua	"getGroundItemProperty(8,'tint')"
		icon lua	"getGroundItemProperty(8,'icon')"
		count lua	"getGroundItemProperty(8,'count')"
		usages lua	"getGroundItemProperty(8,'usages')"
		action "groundItemClick(8)"
		actionAlt "showGroundItemDescription(8)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(8,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}
	button
	{
		area 551 5 52 52
		bam STONSLOT
		tooltip lua	"getGroundItemProperty(9,'name')"
		tint lua	"getGroundItemProperty(9,'tint')"
		icon lua	"getGroundItemProperty(9,'icon')"
		count lua	"getGroundItemProperty(9,'count')"
		usages lua	"getGroundItemProperty(9,'usages')"
		action "groundItemClick(9)"
		actionAlt "showGroundItemDescription(9)"
		actionEnter "mouseOverQuicklootContainer = getSlotContainerId(9,'containerId')"
		actionExit "mouseOverQuicklootContainer = nil"
	}	
}
menu
{
	name 'WORLD_PICKPARTY'
	modal
	align center bottom
	ignoreEsc
	label
	{
		area 0 0 854 134
		mosaic GUWPKPC0
	}
	label
	{
		area 15 4 431 26
		text "REMOVE_MEMBERS_LABEL"
		text style "label"
		align left center
	}
	button
	{
		area 15 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(0)"
		glow lua "worldScreen:GetPickPartyCharacterId(0) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(0)
		"
	}
	button
	{
		area 77 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(1)"
		glow lua "worldScreen:GetPickPartyCharacterId(1) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(1)
		"
	}
	button
	{
		area 139 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(2)"
		glow lua "worldScreen:GetPickPartyCharacterId(2) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(2)
		"
	}
	button
	{
		area 201 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(3)"
		glow lua "worldScreen:GetPickPartyCharacterId(3) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(3)
		"
	}
	button
	{
		area 263 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(4)"
		glow lua "worldScreen:GetPickPartyCharacterId(4) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(4)
		"
	}
	button
	{
		area 325 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(5)"
		glow lua "worldScreen:GetPickPartyCharacterId(5) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(5)
		"
	}
	button
	{
		area 387 26 61 91
		bitmap lua "worldScreen:GetPickPartyPortrait(6)"
		glow lua "worldScreen:GetPickPartyCharacterId(6) == worldScreen:GetPickPartyRemoveCharacterId()"
		action
		"
			worldScreen:OnPickPartyPortraitButtonClick(6)
		"
	}
	label
	{
		area 547 18 91 32
		text lua "game:GetCharacterOverflowCount()"
		text style "normal"
		align center center
	}
	button
	{
		area 638 18 200 44
		bam GUIOSTUM
		text "REMOVE_BUTTON"
		text style "button"
		clickable lua "worldScreen:IsPickPartyRemoveButtonClickable()"
		action
		"
			popup2Button(17518, 'REMOVE_BUTTON', function() worldScreen:RemoveCharacterFromParty() end)
		"
	}
	button
	{
		area 638 62 200 44
		bam GUIOSTLM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "worldScreen:IsPickPartyDoneButtonClickable()"
		on esc
		action
		"
			worldScreen:OnPickPartyDoneButtonClick()
		"
	}
}
`
currentSave = 0
function getSaveBackground(row)
	if(row == currentSave) then
		return "GUISAVEC"
	else
		return "GUISAVEB"
	end
end
function getLoadMenuTitle()
	if (gameSaves.isImporting~=1) then
		return t('LOAD_TITLE')
	end
	return t('IMPORT_TITLE')
end
`

menu
{
	name 'LOAD'
	align center center
	ignoreEsc

	button
	{
		area	0 0 1024 768
		mosaic	GUILOAD --GUISRSVB
		action 
		"
			currentSave = nil
		"
	}
	label
	{
		area 162 16 700 30
		text lua "getLoadMenuTitle()"
		text style "title"
	}
	
	list
	{
		column 
		{ 
			width	73
			label
			{
				area 		0 0 928 -1
				mosaic lua  'getSaveBackground(rowNumber)'
				respectClipping 
				align		center center
			}
			button
			{
				enabled		"gameSaves.files[rowNumber].hasScreenShot"
				area		10 5 60 60
				bitmap res 	"gameSaves.files[rowNumber].screenshot"
				bitmap area	11 15 160 120 
				align		center center
			}

			label
			{
				area	216 21 300 30
				text	lua "gameSaves.files[rowNumber].slotName"
				text style "label"
				align	left top
			}
	
			label
			{
				area	216 55 300 30
				text	lua "gameSaves.files[rowNumber].chapter .. ' ' .. gameSaves.files[rowNumber].time"
				text style "label"
				align	left top
				pad		0 0 -200 0				
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait0"
				area	310 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait0"
				bitmap area	0 0 30 48
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait1"
				area	372 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait1"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait2"
				area	434 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait2"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait3"
				area	496 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait3"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait4"
				area	558 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait4"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait5"
				area	620 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait5"
				bitmap area	0 0 30 48 
				align	center center
			}
		}
		column 
		{ 
			width	27
			label
			{
				area 		-684,0,928,-1
				mosaic lua  'getSaveBackground(rowNumber)'
				respectClipping 
				glow lua 	"rowNumber == currentSave"
				align		center center
			}
			label
			{
				area	8 34 195 100
				text	lua "gameSaves.files[rowNumber].sName "
				text style "label"
				text point 18
				align	center center
			}
		}

		actionDbl
		"
			Infinity_PlaySound('GAM_09')
			loadScreen:LoadGame(gameSaves.files[currentSave].fileName)
		"
		
		area 36 56 954 642
		rowheight	145
		hidehighlight
		table		"gameSaves.files"
		var		currentSave
		scrollbar	'GUISCRC'
	}

	button
	{
		area		622 710 204 44
		bam		GUIOSTLM
		clickable	lua	"currentSave"		
		text		"LOAD_BUTTON"
		text style	"button"
		action
		"
			loadScreen:LoadGame(gameSaves.files[currentSave].fileName)
		"
	}
	button
	{
		enabled		"gameSaves.isImporting ~= 1"
		area		410 710 204 44
		bam		GUIOSTLM
		clickable	lua	"currentSave"		
		text		"DELETE_BUTTON"
		text style	"button"
		action
		"
			popup2Button(15305, 'DELETE_BUTTON',
			 function() loadScreen:DeleteGame(gameSaves.files[currentSave].slotIndex) end)
		"
	}
	button
	{
		area		200 710 204 44
		bam		GUIOSTLM
		text		"BACK_BUTTON"
		text style	"button"
		on escape
		action
		"
			loadScreen:OnMainCancelButtonClick()
		"
	}
}
`
	function compareSaves(s1,s2)
		--return true if s1 comes before s2
		--show the most recent saves first
		return s1.fileTime > s2.fileTime
	end
	function sortSaves()
		table.sort(gameSaves.files,compareSaves)
	end
`
menu
{
	name 'SAVE'
	align center center
	ignoreEsc
	label
	{
		area	0 0 1024 768
		mosaic	GUICREDT --GUISRSVB
		action 
		"
			currentSave = nil
		"
	}
	label
	{
		area 162 16 700 44
		text "SAVE_TITLE"
		text style "title"
	}

	list
	{
		column 
		{ 
			width	73
			label
			{
				area 		0 0 928 -1
				mosaic lua  'getSaveBackground(rowNumber)'
				respectClipping 
				align		center center
			}
			button
			{
				enabled		"gameSaves.files[rowNumber].hasScreenShot"
				area		10 5 60 60
				bitmap res 	"gameSaves.files[rowNumber].screenshot"
				bitmap area	11 15 160 120 
				align		center center
			}

			label
			{
				area	216 18 300 30
				text	lua "gameSaves.files[rowNumber].slotName"
				text style "label"
				align	left top
			}
	
			label
			{
				area	216 52 300 30
				text	lua "gameSaves.files[rowNumber].chapter .. ' ' .. gameSaves.files[rowNumber].time"
				text style "label"
				align	left top
				pad		0 0 -200 0				
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait0"
				area	310 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait0"
				bitmap area	0 0 30 48
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait1"
				area	372 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait1"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait2"
				area	434 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait2"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait3"
				area	496 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait3"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait4"
				area	558 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait4"
				bitmap area	0 0 30 48 
				align	center center
			}
			button
			{
				enabled		 "gameSaves.files[rowNumber].hasPortrait5"
				area	620 84 60 60
				bitmap res "gameSaves.files[rowNumber].portrait5"
				bitmap area	0 0 30 48 
				align	center center
			}
		}
		column 
		{ 
			width	27
			label
			{
				area 		-684,0,928,-1
				mosaic lua  'getSaveBackground(rowNumber)'
				respectClipping 
				glow lua 	"rowNumber == currentSave"
				align		center center
			}
			label
			{
				area	24 0 195 100
				text	lua "gameSaves.files[rowNumber].sName "
				text style "label"
				align	center center
			}
			label
			{
				area		24 70 200 44
				bam 		GUIOSTLM
				frame lua 	"currentCellCheck(2)"
				sequence 	0
				text		"SAVE_BUTTON"
				text style	"button"
		}
		}

		action 
		"
			if cellNumber == 1 then
				cellNumber = nil
			elseif cellNumber == 2 then
				cellNumber = nil
				Infinity_PlaySound('GAM_09')
				Infinity_PushMenu( 'SAVE_NEWSAVE' );
			end
		"

		actionDbl
		"
			Infinity_PlaySound('GAM_09')
			Infinity_PushMenu( 'SAVE_NEWSAVE' );
		"
		
		area 48 252 954 444
		rowheight	145
		table		"gameSaves.files"
		hidehighlight
		var		currentSave
		scrollbar	'GUISCRC'
	}
	button 
	{
		area	48 108 954 148
		mosaic		GUISAVEB
	}
	label
	{
		area	258 124 380 26
		text	'NEW_SAVE_LABEL'
		text style "label"
		text align left center
	}
	button
	{
		area	756 172 200 44
		bam		GUIOSTLM
		text		"SAVE_BUTTON"
		text style	"button"
		action
		"
			--saveScreen:SaveGame(#saveFiles, 'Test Save ' .. #saveFiles)
			currentSave = 0
			Infinity_PushMenu( 'SAVE_NEWSAVE' );
		"
	}

	button
	{
		area		276 714 234 44
		bam			GUIOSTUL
		clickable	lua	"currentSave"		
		text		"DELETE_BUTTON"
		text style	"button"
		action
		"
			popup2Button(15305, 'DELETE_BUTTON',
			 function() saveScreen:DeleteGame(gameSaves.files[currentSave].slotIndex) end)
		"
	}
	button
	{
		area		530 714 234 44
		bam			GUIOSTUR
		text		"BACK_BUTTON"
		text style	"button"
		action
		"
			saveScreen:OnMainCancelButtonClick()
		"
	}
}
`
	newSaveName = ''
	function completeSave()
		Infinity_PopMenu('SAVE_NEWSAVE')
		saveScreen:SaveGame(#gameSaves.files, newSaveName)
	end
	function completeOverwrite()
		Infinity_PopMenu('SAVE_NEWSAVE')
		saveScreen:SaveGame(gameSaves.files[currentSave].slotIndex,newSaveName)
	end

`
menu
{
	name 'SAVE_NEWSAVE'
	align center center
	modal
	onOpen
	"
		bitmapbools = 
		{
			hasScreenShot = 0,
			hasPortrait0 = 0,
			hasPortrait1 = 0,
			hasPortrait2 = 0,
			hasPortrait3 = 0,
			hasPortrait4 = 0,
			hasPortrait5 = 0,
		}
		newSaveName = ''
		if currentSave ~= 0 then
			newSaveName = gameSaves.files[currentSave].slotName
			bitmapbools = 
			{
			hasScreenShot = gameSaves.files[currentSave].hasScreenShot,
			hasPortrait0 = gameSaves.files[currentSave].hasPortrait0,
			hasPortrait1 = gameSaves.files[currentSave].hasPortrait1,
			hasPortrait2 = gameSaves.files[currentSave].hasPortrait2,
			hasPortrait3 = gameSaves.files[currentSave].hasPortrait3,
			hasPortrait4 = gameSaves.files[currentSave].hasPortrait4,
			hasPortrait5 = gameSaves.files[currentSave].hasPortrait5,
			}
		end
		Infinity_FocusTextEdit('newSaveNameArea')

	"
	label
	{
		area	0 0 786 341
		mosaic	GUISRRQB
	}
	label
	{
		area	42 20 722 30
		text	"ENTER_SAVE_LABEL"
		text style "label"
		text align left center
	}
	edit
	{
		name        "newSaveNameArea"
		area		256 76 472 22
		var			newSaveName	
		text style	"edit"
		maxlines	1
		fill        112 111 111 64
		action
		"
			--On return pressed
			if (key_pressed == 13) then
				if(currentSave ~= 0) then
					completeOverwrite()
				else
					completeSave()
				end
				return -1
			end
			return 1
		"
	}
	label
	{
		area	252 110 476 34
		text	lua "gameSaves.currentGameInfo.chapter .. ' ' .. gameSaves.currentGameInfo.time"
		text style "label"
		text align left center
	}
	button
	{
		enabled		 "bitmapbools.hasScreenShot"
		area	66 72 162 142
		bitmap res "gameSaves.files[currentSave].screenshot"
		align	center center
	}
	button
	{
		enabled		 "bitmapbools.hasPortrait0"
		area	356 150 30 48
		bitmap res "gameSaves.files[currentSave].portrait0"
		align	center center
	}
	button
	{
		enabled		 "bitmapbools.hasPortrait1"
		area	418 150 30 48
		bitmap res "gameSaves.files[currentSave].portrait1"
		align	center center
	}
	button
	{
		enabled		 "bitmapbools.hasPortrait2"
		area	482 150 30 48
		bitmap res "gameSaves.files[currentSave].portrait2"	
		align	center center
	}
	button
	{
		enabled		 "bitmapbools.hasPortrait3"
		area	544 150 30 48
		bitmap res "gameSaves.files[currentSave].portrait3"
		align	center center
	}
	button
	{
		enabled		 "bitmapbools.hasPortrait4"
		area	608 150 30 48
		bitmap res "gameSaves.files[currentSave].portrait4"
		align	center center
	}
	button
	{
		enabled		 "bitmapbools.hasPortrait5"
		area	670 150 30 48
		bitmap res "gameSaves.files[currentSave].portrait5"
		align	center center
	}
	button
	{
		area	386 226 302 44
		bam		GUIOSTCL
		text	"SAVE_BUTTON"
		text style "button"
		action
		"
			completeSave()
		"
	}
	button
	{
		enabled	currentSave
		area	386 226 302 44
		bam		GUIOSTCL
		text	"OVERWRITE_BUTTON"
		text style "button"
		action
		"
			completeOverwrite()
		"
	}
	button
	{
		area	386 288 302 44
		bam		GUIOSTCL
		text	"CANCEL_BUTTON"
		text style "button"
		action
		"
			Infinity_PopMenu('SAVE_NEWSAVE')			
		"
	}
}
`
 worldMessageBoxText = ""
 worldMessageBoxLines = 0
 worldMessageBoxClickedOnce = 0
  function dragMessagesY(newY)
	setMessagesY(newY)
	worldMessageBoxClickedOnce = 1
 end
function clampMessageBoxHeight(hNew, hOld)
		if(hNew <= 64) then
			--lower bound on height, sliced rects can't get too small and we don't want to make the message box invisible.
			return hOld - 64
		end
		if(hNew >= 500) then
			--also don't go too high because it looks bad.
			return hOld - 500
		end
		return hOld - hNew
end
 function setMessagesY(newY)
		local x,y,w,hOld = Infinity_GetArea('messagesRect')
		h = hOld - newY
		newY = clampMessageBoxHeight(h,hOld)
		
		adjustItemGroup({"messagesHandleY"},0,newY,0,0)
		adjustItemGroup({"messagesRect","worldMessageBox"},0,newY,0,-newY)
		
		toolbarTop = toolbarTop - newY
		Infinity_SetOffset('WORLD_QUICKLOOT',0, -toolbarTop)
		
		chatboxScrollToBottom = 1
		worldMessageBoxTop = y + newY
 end
 
`
menu
{
	name 'WORLD_MESSAGES'
	align center bottom
	ignoreEsc
	onOpen
	"
		Infinity_SetOffset('WORLD_MESSAGES', 0, -toolbarTop)
		local x,y,w,h = Infinity_GetArea('messagesRect')
		toolbarTop = toolbarTop + h
		setMessagesY(worldMessageBoxTop - y)	
	"
	onClose
	"
		local x,y,w,h = Infinity_GetArea('messagesRect')
		toolbarTop = toolbarTop - h
	"
	label
	{
		name 'messagesRect'
		area 0 111 863 142
		rectangle 4
	}
	button
	{
		area 28 152 816 85
		on pageup
		action
		"
			dragMessagesY(-20)
		"
	}
	button
	{
	 	area 28 152 816 85
		on pagedown
		action
		"
			dragMessagesY(20)
		"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 810 -1
					text lua "combatLog[rowNumber]"
					text style "gamelog"
			}
		}
		name "worldMessageBox"
		area 28 135 816 102
		rowheight dynamic
		table "combatLog"
		hideHighlight
		scrollbar	'GUISCRC'
		scrollbar func "chatboxScroll"
		scrollbar skipReset
	}
	handle
	{
		name 'messagesHandleY'
		area 0 111 863 22
		pulse lua "worldMessageBoxClickedOnce == 0"
		actionDrag
		"
			dragMessagesY(motionY)
		"
	}
}
`
	worldNPCDialogText = ""
	worldPlayerDialogChoices = {}
	glowTest = nil
	startingDialogHeight = 0

	function dialogEntryGreyed()
		return not worldScreen:GetInControlOfDialog()
	end

	function getDesiredDialogHeight()
		--get npc area
		local npcX,npcY,npcW,npcH = Infinity_GetArea('worldNPCDialog')
		
		--get dialog choices height
		local choicesHeight = Infinity_GetListHeight('worldPlayerDialogChoicesList')

		return (20 + choicesHeight + npcH + 20)
	end

	function getCurrentDialogHeight()
		local x,y,w,contentHeight = Infinity_GetArea('worldDialogBackground')
		
		if(showWorldMessages == 1) then
			--Don't include the height of the message log (and its offset) if its active
			local xM,yM,wM,hM = Infinity_GetArea('worldDialogMessageBox')
			local xD,yD,wD,hD = Infinity_GetArea('worldDialogMessageDivider')
			contentHeight = contentHeight - (yD - y)
		end

		return contentHeight
	end

	function resizeDialog()
		buildResponsesList()
		--fit the npc text area to the text height.
		Infinity_ScaleToText("worldNPCDialog")
		
		--get npc area
		local npcX,npcY,npcW,npcH = Infinity_GetArea('worldNPCDialog')
		
		if(npcH > 250) then
			--limit the npc text height to 250
			npcH = 250
			Infinity_SetArea('worldNPCDialog',nil,nil,nil,npcH)
		end	
		
		--Get available height to work in
		local contentHeight = getCurrentDialogHeight()

		local desiredHeight = getDesiredDialogHeight()
		
		--make enough room for the choices and dialog
		if(contentHeight < desiredHeight) then
			resizeDialogContent(contentHeight - desiredHeight)
		else

			local xD,yD,wD,hD = Infinity_GetArea('worldDialogMessageDivider')
			
			--resize the choices list based on the dialog height
			 cH = contentHeight - npcH - (npcY - yD) - 32
			 cY = npcY + npcH + 16
			
			if cH > 50 then
				--set the new list area.
				Infinity_SetArea('worldPlayerDialogChoicesList',nil,cY,nil,cH)
			else
				local heightDifference = 50 - cH
				cY = cY - heightDifference
				cH = cH + heightDifference
				Infinity_SetArea('worldPlayerDialogChoicesList',nil,cY,nil,cH)

				npcH = npcH - heightDifference
				Infinity_SetArea('worldNPCDialog',nil,nil,nil,npcH)
			end
		end
		
	end
	function resizeDialogContent(newY)
		local x,y,w,hOld = Infinity_GetArea('worldDialogBackground')
		local h = hOld - newY
		
		local contentHeight = getCurrentDialogHeight() - newY
		
		if(contentHeight <= 150) then
			--lower bound on height, should leave plenty of room for portrait.
			-- also don't push our toolbar top out of view.
			return
		end
		if(contentHeight >= 500) then
			-- upper bound as well because too high looks bad.
			return
		end
		
		y = y + newY
		Infinity_SetArea('worldDialogBackground',x,y,w,h)
		
		adjustItemGroup({'dialogHandleY', 'worldNPCDialog', 'worldDialogShowMessagesButton', 'worldDialogPortraitArea','worldDialogMessageBox','worldDialogMessageDivider'},0,newY,0,0)
		
		toolbarTop = toolbarTop - newY
		
		resizeDialog()
	end
	function dragDialogMessagesY(newY)
		local x,y,w,hOld = Infinity_GetArea('worldDialogMessageBox')
		local h = hOld - newY
		newY = clampMessageBoxHeight(h,hOld)
		
		--different behavior if the message log is visible.
		adjustItemGroup({'dialogHandleY','worldDialogShowMessagesButton'},0,newY,0,0)
		adjustItemGroup({'worldDialogBackground','worldDialogMessageBox'},0,newY,0,-newY)
		toolbarTop = toolbarTop - newY
		return
	end
	function showMessagesButtonFrame()
		if(showWorldMessages == 1) then return 1 else return 0 end
	end
	function toggleDialogShowMessages()
		if(showWorldMessages == 1) then showWorldMessages = 0 else showWorldMessages = 1 end
		
		local xM,yM,wM,hM = Infinity_GetArea('worldDialogMessageBox')
		local xD,yD,wD,hD = Infinity_GetArea('worldDialogMessageDivider')
		local xB,yB,wB,hB = Infinity_GetArea('worldDialogBackground')
		
		local bgAdjust
		if(showWorldMessages == 1) then
			Infinity_SetArea('worldDialogMessageBox',nil,yB - hM - hD + 8,nil,nil)
			Infinity_SetArea('worldDialogMessageDivider',nil,yB,nil,nil)
		
			bgAdjust = hM + 16 + hD
		else
			bgAdjust = -hM - 16 - hD
		end
		
		adjustItemGroup({'worldDialogBackground'},0,-bgAdjust,0,bgAdjust)
		adjustItemGroup({'dialogHandleY','worldDialogShowMessagesButton'}, 0, -bgAdjust, 0, 0)
		toolbarTop = toolbarTop - bgAdjust
	end
	function getDialogEntryText(row)
		local text = worldPlayerDialogChoices[row].text
		if (row == worldPlayerDialogSelection) then
			--Color the text white when selected
			text = string.gsub(text, "%^0xff212eff", "^0xFFFFFFFF")
		end
		return text
	end
`
menu
{
	name 'WORLD_DIALOG'
	offset 0 -57
	align center bottom
	ignoreEsc
	onOpen
	"	
		local x,y,w,h = Infinity_GetArea('worldDialogBackground')
		toolbarTop = toolbarTop + h
		
		Infinity_PushMenu('WORLD_DIALOG_CONFIRM')
		if(isTouchActionbar() and not dialogViewMode) then
			Infinity_PushMenu('WORLD_DIALOG_LEFT')
			Infinity_PushMenu('WORLD_DIALOG_RIGHT')
		end
		greySidebars()
	"
	onClose
	"
		
		local x,y,w,h = Infinity_GetArea('worldDialogBackground')
		toolbarTop = toolbarTop - h
		resizeDialogContent(h - 253)
		
		Infinity_PopMenu('WORLD_DIALOG_CONFIRM')
		
		Infinity_PopMenu('WORLD_DIALOG_LEFT')
		Infinity_PopMenu('WORLD_DIALOG_RIGHT')
		ungreySidebars()
	"
	label
	{
		name "worldDialogBackground"
		area 0 0 863 253
		rectangle 4
	}
	button
	{
		enabled "showWorldMessages"
		area 28 152 816 85
		on pageup
		action
		"
			local x,y,w,h = Infinity_GetArea('worldDialogBackground')
			dragDialogMessagesY(-20)
		"
	}
	button
	{
		enabled "showWorldMessages"
	 	area 28 152 816 85
		on pagedown
		action
		"
			local x,y,w,h = Infinity_GetArea('worldDialogBackground')
			dragDialogMessagesY(20)
		"
	}
	label
	{
		name "worldDialogPortraitArea"
		area 22 22 54 84
		bitmap lua "worldNPCDialogPortrait"
	}
	text
	{
		name "worldNPCDialog"
		area 84 22 749 38
		text lua "worldNPCDialogText"
		text style "gamelog"
		scrollbar	'GUISCRC'
	}
	text
	{
		name "worldDialogMessageBox"
		enabled "showWorldMessages"
		area 20 -124 813 124
		text lua "worldMessageBoxText"
		text style "gamelog"
		scrollbar	'GUISCRC'
		scrollbar func "chatboxScroll"
	}
	handle
	{
		enabled "showWorldMessages"
		name "dialogHandleY"
		area 0 0 863 32
		actionDrag
		"
			dragDialogMessagesY(motionY)
		"
	}
	text
	{
		name "worldDialogShowMessagesButton"
		area 754 16 62 28
		tooltip lua "t('LOG_HISTORY_TOOLTIP')"
		bam "CHATHIST"
		frame lua "showMessagesButtonFrame()"
		action 
		"
			toggleDialogShowMessages()
		"
	}
	text
	{
		name "worldDialogMessageDivider"
		enabled "showWorldMessages"
		area 33 0 800 8
		mosaic "DLGDIVI"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 -1 -1
				enabled "dialogEntryGreyed()"
				rectangle 1
				rectangle opacity 100
			}
			text
			{
				area 0 0 -1 -1
				text lua "getDialogEntryText(rowNumber)"
				text style "gamelog"
			}
		}
		name "worldPlayerDialogChoicesList"
		area 84 76 749 177
		rowheight dynamic
		hideHighlight
		table "worldPlayerDialogChoices"
		var "worldPlayerDialogSelection"
		scrollbar	'GUISCRC'
		actionEnter
		"
			if(gameOptions.m_bConfirmDialog == true) then return end
			glowTest = mouseoverRow
			worldPlayerDialogSelection = mouseoverRow
		"
		actionExit
		"
			if(gameOptions.m_bConfirmDialog == true) then return end
			glowTest = nil
			worldPlayerDialogSelection = 0
		"
		action
		"
			--In confirm mode, just highlight the choice.
			if(gameOptions.m_bConfirmDialog == true) then return end
			worldScreen:OnDialogReplyClick(worldPlayerDialogChoices[worldPlayerDialogSelection].marker)
			worldPlayerDialogSelection = 0
		"
	}
}
`
function getDialogButtonEnabled()
	if(gameOptions.m_bConfirmDialog == true) then
		return true
	else
		return (#worldPlayerDialogChoices == 0)
	end
end

function getDialogButtonClickable()
	if(gameOptions.m_bConfirmDialog == true) then
		return (#worldPlayerDialogChoices == 0) or (worldPlayerDialogSelection and worldPlayerDialogSelection > 0) --no choices, or we've selected a choice.
	else
		return true
	end
end
`
menu
{
	name 'WORLD_DIALOG_CONFIRM'
	align center bottom
	ignoreEsc
	button
	{
		area 0 0 302 45
		bam GUIOSTCL
		text lua "dialogButtonText"
		enabled "getDialogButtonEnabled()"
		clickable lua "getDialogButtonClickable()"		
		text style "button"
		action 
		"
			if(gameOptions.m_bConfirmDialog == true and (#worldPlayerDialogChoices > 0)) then
				-- if confirm dialog and choices available.
				worldScreen:OnDialogReplyClick(worldPlayerDialogChoices[worldPlayerDialogSelection].marker)
				worldPlayerDialogSelection = 0
			else
				-- no choices, just step.
				worldScreen:StepDialog()
			end
		"
	}
}
	
menu
{
	name 'CHARACTER_SELECT'
	align center center
	onopen "selectedCharacter = 0"
	ignoreesc
	label
	{
		mosaic GUIMPB
		area 0 154 1024 614
	}
	label
	{
		area 32 172 966 50
		text "IMPORT_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 8
			label
			{
				area 0 0 0 100
			}
			label
			{
				area 10 8 54 84
				bitmap lua "character_select[rowNumber].portrait"
			}
		}
		column
		{
			width 92
			label
			{
				area 20 4 -1 -1
				text lua "character_select[rowNumber].name .. '\n' .. character_select[rowNumber].desc" 
				text style "label"
				text align left top
			}
		}

		area 24 244 964 360
		rowheight dynamic
		table "character_select"
		var selectedCharacter
		scrollbar GUISCRC
		action
		"
			Infinity_OnCharacterImportItemSelect(selectedCharacter - 1)
		"
	}
	button
	{
		on escape
		area 194 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action 
		"
			createCharScreen:OnCancelButtonClick()
			Infinity_PopMenu('CHARACTER_SELECT')
		"
	}
	button
	{
		area 438 718 206 44
		bam GUIOSTUM
		text "ACCEPT_BUTTON"
		text style "button"
		clickable 0
	}	
	button
	{
		area 650 718 238 44
		text "DONE_BUTTON" 
		text style "button"
		bam GUIOSTUR
		clickable lua "selectedCharacter ~= 0"
		action 
		"
			createCharScreen:OnDoneButtonClick() 
			Infinity_PopMenu('CHARACTER_SELECT')
		"
	}

}

`
chargen = {

	races = {},
	kits = {},

}
function chargenAcceptOrExport()
	if createCharScreen:GetEngineState() == 4 then
		return t("EXPORT_BUTTON")
	else
		return t("ACCEPT_BUTTON")

	end
end


`
menu
{
	name 'CHARGEN'
	align center center
	ignoreesc
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
	}
	label
	{
		area 64 16 898 44
		text "CHARGEN_TITLE"
		text style "title"
	}
	text
	{
		area 412 180 288 416
		text lua "chargen.information"
		scrollbar 'GUISCRC'
		text style "normal"
	}
	label
	{
		area 775 171 210 330
		bitmap lua "chargen.portrait"
	}

	button
	{
		area 22 226 340 30
		bam GUICHLNG
		sequence 0
		clickable lua "createCharScreen:GetCurrentStep() == 0"
		glow lua "createCharScreen:GetCurrentStep() == 0"
		text "GENDER_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}
	button
	{
		area 22 256 340 30
		bam GUICHLNG
		sequence 1
		clickable lua "createCharScreen:GetCurrentStep() == 3"
		glow lua "createCharScreen:GetCurrentStep() == 3"
		text "RACE_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}
	button
	{
		area 22 286 340 30
		bam GUICHLNG
		sequence 2
		clickable lua "createCharScreen:GetCurrentStep() == 4"
		glow lua "createCharScreen:GetCurrentStep() == 4"
		text "CLASS_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}
	button
	{
		area 22 316 340 30
		bam GUICHLNG
		sequence 1
		clickable lua "createCharScreen:GetCurrentStep() == 7"
		glow lua "createCharScreen:GetCurrentStep() == 7"
		text "ALIGNMENT_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}

	button
	{
		area 22 346 340 30
		bam GUICHLNG
		sequence 0
		clickable lua "createCharScreen:GetCurrentStep() == 8"
		glow lua "createCharScreen:GetCurrentStep() == 8"
		text "ABILITIES_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}
	button
	{
		area 22 376 340 30
		bam GUICHLNG
		sequence 1
		clickable lua "createCharScreen:GetCurrentStep() == 9"
		glow lua "createCharScreen:GetCurrentStep() == 9"
		text "SKILLS_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}
	button
	{
		area 22 406 340 30
		bam GUICHLNG
		sequence 2
		clickable lua "createCharScreen:GetCurrentStep() == 15"
		glow lua "createCharScreen:GetCurrentStep() == 15"
		text "APPEARANCE_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}
	button
	{
		area 22 436 340 30
		bam GUICHLNG
		sequence 1
		clickable lua "createCharScreen:GetCurrentStep() == 17"
		glow lua "createCharScreen:GetCurrentStep() == 17"
		text "NAME_BUTTON"
		text style "button"
		action "createCharScreen:OnMenuButtonClick()"
	}

	button
	{
		area 770 552 204 44
		text "IMPORT_BUTTON"
		text style "button"
		bam GUIOSTUM
		clickable lua "Infinity_GetCurrentScreenName() == 'CHARGEN'"
		action "createCharScreen:OnImportCharacterButtonClick()"
	}
	button
	{
		area 770 604 204 44
		text "BIOGRAPHY_BUTTON"
		text style "button"
		bam GUIOSTLM
		clickable lua "createCharScreen:GetCurrentStep() >= 17"
		action "createCharScreen:OnBiographyButtonClick()"
	}
	button
	{
		on escape
		area 194 718 232 44
		text "BACK_BUTTON"
		text style "button"
		bam GUIOSTUL
		clickable lua "createCharScreen:IsMainBackButtonClickable()"
		action "createCharScreen:OnMainBackButtonClick()"
	}
	button
	{
		on escape
		area 194 718 232 44
		text "CANCEL_BUTTON"
		text style "button"
		bam GUIOSTUL
		enabled "not createCharScreen:IsMainBackButtonClickable()"
		action "createCharScreen:OnMainCancelButtonClick()"
	}
	button
	{
		area 438 718 206 44
		text lua "chargenAcceptOrExport()"
		text style "button"
		bam GUIOSTUM
		clickable lua "createCharScreen:IsChargenComplete()"
		action "createCharScreen:AcceptCharacter(-1)"
	}
	button
	{
		area 650 718 238 44
		text "CREATE_PARTY_BUTTON"
		text style "button"
		bam GUIOSTUR
		clickable lua "createCharScreen:IsAdvancedButtonClickable() == true"
		action "createCharScreen:OnAdvancedButtonClick()"
	}
}

`
createCharGenderHelp = 17236
`
menu
{
	name 'CHARGEN_GENDER'
	align center center
	ignoreesc
	onOpen "toggleMale = 0; toggleFemale = 0"
	
	label
	{
		area 0 159 1024 609
		mosaic 'GUIGDB'
	}
	label
	{
		area 22 164 332 44
		text "GENDER_TITLE"
		text style "title"
	}
	label
	{
		area 414 182 288 416
		text lua "Infinity_FetchString(createCharGenderHelp)" 
		text style "normal"
	}
	button
	{
		area 78 354 98 86
		bam GUIGEND1
		sequence 0
		toggle toggleMale
		action "toggleFemale = 0; createCharScreen:OnGenderSelectButtonClick(1)"
	}
	button
	{
		area 200 354 98 86
		bam GUIGEND1
		sequence 1
		toggle toggleFemale
		action "toggleMale = 0; createCharScreen:OnGenderSelectButtonClick(2)"
	}

	button
	{
		on escape
		area 194 718 232 44
		text "BACK_BUTTON"
		text style "button"
		bam GUIOSTUL
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}
}

menu
{
	name 'CHARGEN_PORTRAIT'
	align center center
	ignoreesc
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 92 1024 676
		mosaic 'GUIAPB'
	}
	label
	{
		area 28 172 304 44
		text "APPEARANCE_TITLE"
		text style "title"
	}
	button
	{
		area 280 302 52 132
		bam GUIPRC
		sequence 0
		action "createCharScreen:DecCurrentPortrait()"
	}
	button
	{
		area 692 302 52 132
		bam GUIPRC
		sequence 1
		action "createCharScreen:IncCurrentPortrait()"
	}

	label
	{
		area 406 206 212 330
		bitmap lua "createCharScreen:GetCurrentPortrait()"
	}

	button
	{
		area 358 648 300 44
		bam GUIOSTCL
		text "CUSTOM_BUTTON"
		text style "button"
		enabled "not e:IsTouchUI()"
		action "
			TEXT_popup_big = 17188
			Infinity_PushMenu('POPUP_BIG')
			"
	}

	button
	{
		on escape
		area 194 718 232 44
		text "BACK_BUTTON"
		text style "button"
		bam GUIOSTUL
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}

`
function raceOrGeneralHelp()
	race = chargen.races[currentChargenRace]
	if race then
		return Infinity_FetchString(race.desc)
	else
		return Infinity_FetchString(17237)
	end
end
`
menu
{
	name 'CHARGEN_RACE'
	align center center
	ignoreesc
	onopen "currentChargenRace = nil"
	label
	{
		area 0 159 1024 609
		mosaic 'GUISMF'
	}
	label
	{
		area 22 164 334 44
		text "RACE_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 340 44
				text lua "Infinity_FetchString(chargen.races[rowNumber].name)"
				text style "list"
				pad 8 0 0 0
				text lower
				
			}
		}
		action "
			if chargen.races[currentChargenRace] then
				createCharScreen:OnRaceSelectButtonClick(chargen.races[currentChargenRace].id)
			end
			"
		rowheight 44
		area 26 222 336 382
		table "chargen.races"
		var currentChargenRace
		scrollbar	'GUISCRC'
	}
	text
	{
		area 412 182 576 412
		text lua "raceOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	button
	{
		on escape
		area 194 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}
`
function classOrGeneralHelp()
	class = chargen.class[currentChargenClass]
	if class then
		return Infinity_FetchString(class.desc)
	else
		--only bit that may need to change for dual class! :)
		return Infinity_FetchString(17242)
	end
end
`
menu
{
	name 'CHARGEN_CLASS'
	align center center
	ignoreesc
	onopen "currentChargenClass = nil"
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 159 1024 609
		mosaic GUISMF
	}
	label
	{
		area 22 166 334 44
		text "CLASS_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 340 44
				text lua "Infinity_FetchString(chargen.class[rowNumber].name)"
				text style "list"
				pad 8 0 0 0
				text lower
				
			}
		}
		action "
			if chargen.class[currentChargenClass] then
				createCharScreen:OnClassSelectButtonClick(chargen.class[currentChargenClass].id)
			end
			"
		rowheight 44
		area 26 222 336 382
		table "chargen.class"
		var currentChargenClass
		scrollbar 'GUISCRC'
	}
	text
	{
		area 414 182 574 414
		text lua "classOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	button
	{
		on escape
		area 194 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		clickable lua "createCharScreen:GetCurrentStep() ~= const.STEP_DUALCLASS_CLASS"
		action "createCharScreen:OnCancelButtonClick(); Infinity_PopMenu('CHARGEN_CLASS');"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "createCharScreen:OnDoneButtonClick(); Infinity_PopMenu('CHARGEN_CLASS'); "
	}

}
`
function kitOrGeneralHelp()
	kit = chargen.kit[currentChargenKit]
	if kit then
		return Infinity_FetchString(kit.desc)
	else
		return Infinity_FetchString(17242)
	end
end
`
menu
{
	name 'CHARGEN_KIT'
	align center center
	ignoreesc
	label
	{
		area 0 159 1024 609
		mosaic GUISMF
	}
	label
	{
		area 22 166 334 44
		text "CLASS_KIT_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 340 44
				text lua "Infinity_FetchString(chargen.kit[rowNumber].name)"
				text style "list"
				pad 8 0 0 0
				text lower
				
			}
		}
		action "
			if chargen.kit[currentChargenKit] then
				createCharScreen:OnKitSelectButtonClick(chargen.kit[currentChargenKit].id)
			end
			"
			
		rowheight 44
		area 26 222 336 382
		table "chargen.kit"
		var currentChargenKit
		scrollbar	'GUISCRC'
	}
	text
	{
		area 414 182 574 414
		text lua "kitOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	button
	{
		on escape
		area 194 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}
`
function alignmentOrGeneralHelp()
	alignment = chargen.alignment[currentChargenAlignment]
	if alignment then
		return Infinity_FetchString(alignment.desc)
	else
		return Infinity_FetchString(9602)
	end
end
`
menu
{
	name 'CHARGEN_ALIGNMENT'
	align center center
	ignoreesc
	onopen "currentChargenAlignment = nil"
	label
	{
		area 0 159 1024 609
		mosaic GUISMF
	}
	label
	{
		area 22 168 332 44
		text "ALIGNMENT_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 340 44
				text lua "Infinity_FetchString(chargen.alignment[rowNumber].name)"
				text style "list"
				pad 8 0 0 0
				text lower
				
			}
		}
		action "
			if chargen.alignment[currentChargenAlignment] then
				createCharScreen:OnAlignmentSelectButtonClick(chargen.alignment[currentChargenAlignment].id)
			end
			"
		rowheight 40
		area 26 222 336 382
		table "chargen.alignment"
		var currentChargenAlignment
		scrollbar	'GUISCRC'
	}
	text
	{
		area 412 180 576 416
		text lua "alignmentOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	button
	{
		on escape
		area 194 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}
`
chargen.ability = {
	{name = 'STRENGTH_LABEL', desc = 9582},
	{name = 'DEXTERITY_LABEL', desc = 9584},
	{name = 'CONSTITUTION_LABEL', desc = 9583},
	{name = 'INTELLIGENCE_LABEL', desc = 9585},
	{name = 'WISDOM_LABEL', desc = 9586},
	{name = 'CHARISMA_LABEL', desc = 9587},
}

function abilityOrGeneralHelp()
	ability = chargen.ability[currentChargenAbility]
	if ability and ability.desc ~= -1 then
		createCharScreen:SetAbilityHelpInfo(currentChargenAbility)
		return Infinity_FetchString(ability.desc)
	else
		return Infinity_FetchString(17247)
	end
end

`

menu
{
	name 'CHARGEN_ABILITIES'
	align center center
	ignoreesc
	onopen "ticksPassed = 0; ticksStarting = 0"
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 156 1024 612
		mosaic GUISMDB
	}
	label
	{
		area 20 174 496 48
		text "ABILITIES_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 60
			label
			{
				area 0 0 290 55
				text lua "t(chargen.ability[rowNumber].name)"
				text style "normal"
				align right center
				
			}
		}
		column
		{
			width 22
			label
			{
				area 20 0 90 55
				text lua "chargen.ability[rowNumber].roll"
				text style "normal"
				align center center
			}
		}
		column
		{
			width 9
			label
			{
				area 0 6 45 42
				bam GUIOSW
				frame lua "currentCellCheck(3)"
				sequence 0
			}
		}
		column
		{
			width 16
			label
			{
				area 0 6 45 42
				bam GUIOSW
				frame lua "currentCellCheck(4)"
				sequence 1

			}
		}
		action 
		"
			if ticksStarting < 10 then
				if cellNumber == 3 then
					createCharScreen:OnAbilityPlusMinusButtonClick(currentChargenAbility, true)
				elseif cellNumber == 4 then
					createCharScreen:OnAbilityPlusMinusButtonClick(currentChargenAbility, false)
				end
			end
			cellNumber = nil
			ticksPassed = 0
			ticksStarting = 0
		"
		actionUpdate "
			ticksStarting = ticksStarting + 1
			if ticksStarting > 10 then
				ticksPassed = ticksPassed + 1
				if ticksPassed > 7 then
					if cellNumber == 3 then
						createCharScreen:OnAbilityPlusMinusButtonClick(currentChargenAbility, true)
					elseif cellNumber == 4 then
						createCharScreen:OnAbilityPlusMinusButtonClick(currentChargenAbility, false)
					end
					ticksPassed = 0
				end
			end
		"

		rowheight 52
		hidehighlight
		area 32 254 496 320
		table "chargen.ability"
		var currentChargenAbility
	}
	label
	{
		area 152 568 186 54
		text "TOTAL_ROLL_NORMAL"
		text style "normal"
		text align right center
	}
	label
	{
		area 368 568 50 54
		text lua "chargen.totalRoll"
		text style "normal"
		text align center center
	}
	label
	{
		area 434 568 94 54
		text lua "chargen.extraAbilityPoints"
		text style "normal"
		text align center center
	}


	text
	{
		area 582 196 404 400
		text lua "abilityOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}

	button
	{
		area 378 642 142 40
		bam GUIOSTSM
		sequence 0
		text "REROLL_BUTTON"
		text style "button"
		action "createCharScreen:OnAbilityReRollButtonClick()"
	}
	button
	{
		area 60 642 142 40
		bam GUIOSTSM
		sequence 0
		text "STORE_BUTTON"
		text style "button"
		action "createCharScreen:OnAbilityStoreButtonClick()"
	}
	button
	{
		area 220 642 142 40
		bam GUIOSTSM
		sequence 0
		text "RECALL_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsAbilityRecallButtonClickable()"
		action "createCharScreen:OnAbilityRecallButtonClick()"
	}

	button
	{
		on '8'
		action "createCharScreen:OnCheatyMcCheaterson()"
		
		
	}

	button
	{
		on escape
		area 194 716 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 720 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}

`
function proficiencyOrGeneralHelp()
	local prof = chargen.proficiency[currentChargenProficiency]
	local skill = chargen.thief_skill[currentChargenThiefSkill]
	if prof and prof.desc ~= -1 then
		return Infinity_FetchString(prof.desc)
	elseif skill and skill.desc ~= -1 then
		return Infinity_FetchString(skill.description)
	else
		if(chargen.levelingUp) then
			if(levelUpInfoToggle == 1) then
				return chargen.charInfo
			else
				return chargen.levelInfo
			end
		else
		return Infinity_FetchString(9588)
	end
	end
end

function getProficienciesTitle()
	if(chargen.levelingUp) then
		return t("LEVEL_UP_TITLE")
	else
		return t("CHARGEN_TITLE")
	end
end

function isChargenProficienciesBackButtonClickable()
	return ((not chargen.levelingUp) and createCharScreen:GetCurrentStep() ~= const.STEP_DUALCLASS_PROFICIENCIES)
end
`

menu
{
	name 'CHARGEN_PROFICIENCIES'
	modal
	align center center
	ignoreesc
	onopen "currentChargenProficiency = nil; currentChargenThiefSkill = nil; ticksPassed = 0; ticksStarting = 0"
	label
	{
		area 0 0 1024 768
		mosaic GUILUPB
	}
	label
	{
		area 162 16 700 44
		text lua "getProficienciesTitle()"
		text style "title"
	}
	label
	{
		area 58 172 392 44
		text "PROF_SLOTS_LABEL"
		text style "label"
		text align left bottom
	}
	label
	{
		area 450 172 50 44
		text lua "chargen.extraProficiencySlots"
		text style "label"
		text align center bottom
	}
	label
	{
		area 578 172 318 44
		text "SKILLS_LABEL"
		text style "label"
		text align left bottom
	}
	label
	{
		area 896 172 50 44
		text lua "chargen.extraSkillPoints"
		text style "label"
		text align center bottom
	}

	list
	{
		column
		{
			width 62
			label
			{
				area 0 0 280 55
				text lua "Infinity_FetchString(chargen.proficiency[rowNumber].name)"
				text style "normal"
				align right center
				
			}
		}
		column
		{
			width 4
			label
			{
				bam GUIPFC
				area 0 19 16 16
				align center center
				enabled "chargen.proficiency[rowNumber].value > 4"
			}
		}
		column
		{
			width 4
			label
			{
				bam GUIPFC
				area 0 19 16 16
				align center center
				enabled "chargen.proficiency[rowNumber].value > 3"
			}
		}
		column
		{
			width 4
			label
			{
				bam GUIPFC
				area 0 19 16 16
				align center center
				enabled "chargen.proficiency[rowNumber].value > 2"
			}
		}
		column
		{
			width 4
			label
			{
				bam GUIPFC
				area 0 19 16 16
				align center center
				enabled "chargen.proficiency[rowNumber].value > 1"
			}
		}
		column
		{
			width 4
			label
			{
				bam GUIPFC
				area 0 19 16 16
				align center center
				enabled "chargen.proficiency[rowNumber].value > 0"
			}
		}

		column
		{
			width 9
			label
			{
				area 0 6 45 42
				bam GUIOSW
				frame lua "getPlusFrame(7)"
				sequence 0
				align center center
			}
		}
		column
		{
			width 9
			label
			{
				area 0 6 45 42
				bam GUIOSW
				sequence 1
				frame lua "getMinusFrame(8)"

				align center center
			}
		}

		action "
			currentChargenThiefSkill = nil
			if ticksStarting < 10 then
				if cellNumber == 7 and plusButtonClickable(currentChargenProficiency) then
					createCharScreen:OnProficiencyPlusMinusButtonClick(chargen.proficiency[currentChargenProficiency].id, true)
				elseif cellNumber == 8 and minusButtonClickable(currentChargenProficiency) then
					createCharScreen:OnProficiencyPlusMinusButtonClick(chargen.proficiency[currentChargenProficiency].id, false)
				end
			end
			cellNumber = nil
			ticksPassed = 0
			ticksStarting = 0
		"
		actionUpdate "
			currentChargenThiefSkill = nil
			ticksStarting = ticksStarting + 1
			if ticksStarting > 10 then
				ticksPassed = ticksPassed + 1
				if ticksPassed > 7 then
					if cellNumber == 7 and plusButtonClickable(currentChargenProficiency) then
						createCharScreen:OnProficiencyPlusMinusButtonClick(chargen.proficiency[currentChargenProficiency].id, true)
					elseif cellNumber == 8 and minusButtonClickable(currentChargenProficiency) then
						createCharScreen:OnProficiencyPlusMinusButtonClick(chargen.proficiency[currentChargenProficiency].id, false)
					end
					ticksPassed = 0
				end
			end
		"

		rowheight 54
		area 37 248 523 432
		table "chargen.proficiency"
		var currentChargenProficiency
		scrollbar	'GUISCRC'

	}
	list
	{
		column
		{
			width 60
			label
			{
				area 0 0 180 54
				text lua "Infinity_FetchString(chargen.thief_skill[rowNumber].name)"
				text style "normal"
				text align right center
				
			}
		}
		column
		{
			width 10
			label
			{
				area 0 0 40 54
				text lua "chargen.thief_skill[rowNumber].value"
				text style "normal"
				text align left center

			}
		}
		column
		{
			width 18
			label
			{
				area 24 6 45 42
				bam GUIOSW
				enabled "createCharScreen:IsThiefSkillPlusMinusButtonClickable()"
				frame lua "currentCellCheck(3)"
				sequence 0
			}
		}
		column
		{
			width 12
			label
			{
				area 0 6 45 42
				bam GUIOSW
				enabled "createCharScreen:IsThiefSkillPlusMinusButtonClickable()"
				frame lua "currentCellCheck(4)"
				sequence 1

			}
		}

		action 
		"
			currentChargenProficiency = nil
			if ticksStarting < 10 then
				if createCharScreen:IsThiefSkillPlusMinusButtonClickable() then
					if cellNumber == 3 then
						createCharScreen:OnThiefSkillPlusMinusButtonClick(chargen.thief_skill[currentChargenThiefSkill].id, true)
					elseif cellNumber == 4 then
						createCharScreen:OnThiefSkillPlusMinusButtonClick(chargen.thief_skill[currentChargenThiefSkill].id, false)
					end
				end
			end
			cellNumber = nil
			ticksPassed = 0
			ticksStarting = 0
		"
		actionUpdate 
		"
			currentChargenProficiency = nil
			if createCharScreen:IsThiefSkillPlusMinusButtonClickable() then
				ticksStarting = ticksStarting + 1
				if ticksStarting > 10 then
					ticksPassed = ticksPassed + 1
					if ticksPassed > 2 then
						if cellNumber == 3 then
							createCharScreen:OnThiefSkillPlusMinusButtonClick(chargen.thief_skill[currentChargenThiefSkill].id, true)
						elseif cellNumber == 4 then
							createCharScreen:OnThiefSkillPlusMinusButtonClick(chargen.thief_skill[currentChargenThiefSkill].id, false)
						end
						ticksPassed = 0
					end
				end
			end
		"

		rowheight 54
		area 574 262 418 210
		table "chargen.thief_skill"
		var currentChargenThiefSkill
		scrollbar	'GUISCRC'
	}

	text
	{
		area 570 490 416 194
		text lua "proficiencyOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	
	button
	{
		enabled "chargen.levelingUp"
		area 360 70 302 44
		bam GUIOSTCL
		text "INFORMATION_BUTTON"
		text style "button"
		toggle "levelUpInfoToggle"
		action
		"
			currentChargenProficiency = nil
		"
	}
	button
	{
		enabled "chargen.levelingUp"
		area 650 718 238 44
		bam GUIOSTUR
		text "HIGH_LEVEL_ABILITIES_BUTTON"
		text style "button"
		toggle "levelUpInfoToggle"
		clickable lua "createCharScreen:IsHighLevelAbilitiesButtonClickable()"
		action
		"
			createCharScreen:OnHighLevelAbilitiesButtonClick()
		"
	}
	button
	{
		on escape
		area 194 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		clickable lua "isChargenProficienciesBackButtonClickable()"
		action "createCharScreen:OnCancelButtonClick();"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "createCharScreen:OnDoneButtonClick();"
	}
	button
	{
		enabled "not chargen.levelingUp"
		area 650 718 238 44
		bam GUIOSTUR
		clickable 0
		text "CREATE_PARTY_BUTTON"
		text style "button"
	}

}
`
function specialistFrame(num)
	if spellBook[chargen.currentSpellLevelChoice][chargen.choose_spell[num].key].specialist then
		return 3
	end
	return 0
end
function spellLearnOrUnlearnText()
	if currentChargenChooseMageSpell == nil or not chargen.choose_spell[currentChargenChooseMageSpell].enabled then
		return t("BUTTON_LEARN")
	else
		return t("BUTTON_UNLEARN")
	end
end
function spellLearnOrUnlearnClickable()
	spl = chargen.choose_spell[currentChargenChooseMageSpell]
	if chargen.extraSpells == 0 and spl ~= nil and spl.enabled == false or spl == nil or spl.known then
		return false
	else
		return true 
	end
end


function chooseSpellOrGeneralHelp()
	local helpText = chargen.helpText
	spl = chargen.choose_spell[currentChargenChooseMageSpell]
	if spl == nil then
		return helpText
	end

	local desc = spellBook[chargen.currentSpellLevelChoice][spl.key].desc
	if currentChargenChooseMageSpell and desc ~= -1 then
		return Infinity_FetchString(desc)
	else
		return helpText
	end
end

function nextOrDone()
	if(createCharScreen:HasMoreMageLevels()) then
		return t('NEXT_BUTTON')
	else
		return t('DONE_BUTTON')
	end
end
function shouldShowSpecialistMessage()
	local ret = false

	if chargen.extraSpells == 0 and not createCharScreen:IsDoneButtonClickable() then
		ret = true
	end

	return ret
end
`
menu
{
	name 'CHARGEN_CHOOSE_SPELLS'
	align center center
	ignoreesc
	onOpen 
	"
		table.sort(chargen.choose_spell, sortBySpellName)
		currentChargenChooseMageSpell = nil

		if currentChargenKit == nil then
			currentChargenKit = 0
		end

		local currentKitName = ''

		--gnome illusionists
		if currentChargenRace ~= 6 and chargen.kit then
			currentKitName = Infinity_FetchString(chargen.kit[currentChargenKit].name)
		else
			currentKitName = Infinity_FetchString(2862)
		end
		
		if currentKitName == Infinity_FetchString(597) then
			setStringTokenLua('<SCHOOLTOKEN>',t('ABJURATION_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(2179) then
			setStringTokenLua('<SCHOOLTOKEN>',t('CONJURATION_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(2846) then
			setStringTokenLua('<SCHOOLTOKEN>',t('DIVINATION_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(2861) then
			setStringTokenLua('<SCHOOLTOKEN>',t('ENCHANTMENT_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(2862) then
			setStringTokenLua('<SCHOOLTOKEN>',t('ILLUSION_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(3015) then
			setStringTokenLua('<SCHOOLTOKEN>',t('EVOCATION_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(12744) then
			setStringTokenLua('<SCHOOLTOKEN>',t('NECROMANCY_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(12745) then
			setStringTokenLua('<SCHOOLTOKEN>',t('TRANSMUTATION_SCHOOL_TOKEN'))
		elseif currentKitName == Infinity_FetchString(54893) then
			setStringTokenLua('<SCHOOLTOKEN>',Infinity_FetchString(54893))
		end
	"
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 156 1024 612
		mosaic GUISMS
	}
	label
	{
		area 32 170 270 52
		text lua "t(chargen.title) .. ': ' .. t('LEVEL_LABEL') .. ' ' .. chargen.currentSpellLevelChoice"
		text style "title"
	}
	list
	{
		column
		{
			width 16

			label
			{
				bam GUIPFC
				area 4 19 16 16
				align center center
				enabled "chargen.choose_spell[rowNumber].enabled or chargen.choose_spell[rowNumber].known"
			}
			label
			{
				bam GUIBTBUT
				area 20 0 52 52 
				align center center
				frame lua "specialistFrame(rowNumber)"
			}
			label
			{
				area 20 0 52 52
				greyscale lua "chargen.choose_spell[rowNumber].enabled == false"
				bam lua "spellBook[chargen.currentSpellLevelChoice][chargen.choose_spell[rowNumber].key].groundicon"
				align center center
			}
		}
		column
		{
			width 84
			label
			{
				area 4 0 -1 -1
				text lua "Infinity_FetchString(spellBook[chargen.currentSpellLevelChoice][chargen.choose_spell[rowNumber].key].name)"
				text style "normal"

				glow lua "chargen.choose_spell[rowNumber].enabled"
				align left center
				
			}
		}

		scrollbar	'GUISCRC'
		rowheight 52
		area 32 244 492 376
		table "chargen.choose_spell"
		var currentChargenChooseMageSpell
		action "
			if cellNumber == 1 and not chargen.choose_spell[currentChargenChooseMageSpell].known then
				createCharScreen:OnLearnMageSpellButtonClick(currentChargenChooseMageSpell)
			end
		"
	}
	text
	{
		area 580 196 406 334
		text lua "chooseSpellOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}

	label
	{
		area 316 174 168 48
		text "SPELLS_REMAINING_NORMAL"
		text style "normal"
		text align right center
	}
	label
	{
		area 484 174 36 48
		text lua "chargen.extraSpells"
		text style "normal"
		text align center center
	}
	label
	{
		area 598 568 360 40
		enabled "shouldShowSpecialistMessage()"
		text lua "t('SPECIALIST_SPELL_REQ')"
		text style "normal"
		text align center center
		rectangle 0
	}

	button
	{
		area 566 636 206 44
		bam GUIOSTUM
		text lua "spellLearnOrUnlearnText()"
		text style "button"
		clickable lua "spellLearnOrUnlearnClickable()"
		action "createCharScreen:OnLearnMageSpellButtonClick(currentChargenChooseMageSpell)"
	}

	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		clickable lua "not chargen.levelingUp"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "createCharScreen:OnDoneButtonClick()"
	}

}
`

function mageMemorizeSpellOrGeneralHelp()
	spl = chargen.choose_spell[currentChargenMemorizeMageSpell]
	if spl == nil then
		return Infinity_FetchString(17253)
	end

	local desc = mageSpells[chargen.currentSpellLevelChoice][spl.key].desc
	if currentChargenMemorizeMageSpell and desc ~= -1 then
		return Infinity_FetchString(desc)
	else
		return Infinity_FetchString(17253)
	end
end

`
menu
{
	name 'CHARGEN_MEMORIZE_MAGE'
	align center center
	ignoreesc
	onOpen "
		table.sort(chargen.choose_spell, sortByMageSpellName)
		currentChargenMemorizeMageSpell = nil
		"
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 156 1024 612
		mosaic GUISMS
	}
	label
	{
		area 32 170 270 52
		text lua "chargen.title"
		text style "title"
	}
	list
	{
		column
		{
			width 12

			label
			{
				bam GUIBTBUT
				area 0 0 52 52 
				align center center
				icon lua "mageSpells[chargen.currentSpellLevelChoice][chargen.choose_spell[rowNumber].key].groundicon"
				frame lua "specialistFrame(rowNumber)"
				count lua "chargen.choose_spell[rowNumber].count"
			}
		}
		column
		{
			width 68
			label
			{
				area 4 0 -1 -1
				text lua "Infinity_FetchString(mageSpells[chargen.currentSpellLevelChoice][chargen.choose_spell[rowNumber].key].name)"
				text style "normal"

				glow lua "chargen.choose_spell[rowNumber].enabled"
				align left center
				
			}
		}
		column
		{
			width 10
			label
			{
				area 0 4 45 42
				bam GUIOSW
				frame lua "currentCellCheck(3)"
				sequence 0
			}
		}
		column
		{
			width 10
			label
			{
				area 0 4 45 42
				bam GUIOSW
				frame lua "currentCellCheck(4)"
				sequence 1

			}
		}


		scrollbar	'GUISCRC'
		rowheight 52
		area 34 248 492 370
		table "chargen.choose_spell"
		var currentChargenMemorizeMageSpell
		action "
			if cellNumber == 3 then
				createCharScreen:OnMemorizeMageSpellButtonClick(currentChargenMemorizeMageSpell, 1)
			elseif cellNumber == 4 then
				createCharScreen:OnMemorizeMageSpellButtonClick(currentChargenMemorizeMageSpell, -1)
			end
			cellNumber = nil
		"
	}
	text
	{
		area 580 196 404 334
		text lua "mageMemorizeSpellOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}

	label
	{
		area 316 174 168 48
		text "SPELLS_REMAINING_NORMAL"
		text style "normal"
		text align right center
	}
	label
	{
		area 484 174 36 48
		text lua "chargen.extraSpells"
		text style "normal"
		text align center center
	}

	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text lua "nextOrDone()"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "createCharScreen:OnDoneButtonClick()"
	}

}
`

function priestMemorizeSpellOrGeneralHelp()
	spl = chargen.choose_spell[currentChargenMemorizePriestSpell]
	if spl == nil then
		return Infinity_FetchString(17253)
	end

	local desc = priestSpells[chargen.currentSpellLevelChoice][spl.key].desc
	if currentChargenMemorizePriestSpell and desc ~= -1 then
		return Infinity_FetchString(desc)
	else
		return Infinity_FetchString(17253)
	end
end

`
menu
{
	name 'CHARGEN_MEMORIZE_PRIEST'
	align center center
	ignoreesc
	onOpen "
		table.sort(chargen.choose_spell, sortByPriestSpellName)
		currentChargenMemorizePriestSpell = nil
		"
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 156 1024 612
		mosaic GUISMS
	}
	label
	{
		area 32 170 270 52
		text lua "chargen.title"
		text style "title"
	}
	list
	{
		column
		{
			width 12

			label
			{
				bam GUIBTBUT
				area 0 0 52 52 
				align center center
				icon lua "priestSpells[chargen.currentSpellLevelChoice][chargen.choose_spell[rowNumber].key].groundicon"
				frame 0
				count lua "chargen.choose_spell[rowNumber].count"
			}
		}
		column
		{
			width 68
			label
			{
				area 4 0 -1 -1
				text lua "Infinity_FetchString(priestSpells[chargen.currentSpellLevelChoice][chargen.choose_spell[rowNumber].key].name)"
				text style "normal"

				glow lua "chargen.choose_spell[rowNumber].enabled"
				align left center
				
			}
		}
		column
		{
			width 10
			label
			{
				area 0 4 45 42
				bam GUIOSW
				sequence 0
			}
		}
		column
		{
			width 10
			label
			{
				area 0 4 45 42
				bam GUIOSW
				sequence 1

			}
		}


		scrollbar	'GUISCRC'
		rowheight 52
		area 34 246 492 374
		table "chargen.choose_spell"
		var currentChargenMemorizePriestSpell
		action "
			if cellNumber == 3 then
				createCharScreen:OnMemorizePriestSpellButtonClick(currentChargenMemorizePriestSpell, 1)
			elseif cellNumber == 4 then
				createCharScreen:OnMemorizePriestSpellButtonClick(currentChargenMemorizePriestSpell, -1)
			end
		"
	}
	text
	{
		area 572 190 420 346
		text lua "priestMemorizeSpellOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}

	label
	{
		area 316 174 168 48
		text "SPELLS_REMAINING_NORMAL"
		text style "normal"
		text align right center
	}
	label
	{
		area 484 174 36 48
		text lua "chargen.extraSpells"
		text style "normal"
		text align center center
	}

	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text lua "nextOrDone()"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "createCharScreen:OnDoneButtonClick()"
	}

}
`
currentChargenCustomSound = 0

`
menu
{
	name 'CHARGEN_CUSTOMSOUNDS'
	align center center
	ignoreesc
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 162 1024 606
		mosaic 'GU3MPB'
	}
	label
	{
		area	24 174 408 44
		text	"SOUND_TITLE"
		text style	title
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 384 18
				text lua "getFileNameStringRef(rowNumber, chargen.customSound)"
				text style	"list"
				pad 8 0 0 0
			}
		}
		area 20 242 412 362
		rowheight	18
		table		"chargen.customSound"
		var			"currentChargenCustomSound"
		scrollbar	'GUISCRC'
		action
		"
			createCharScreen:OnSoundItemSelect(currentChargenCustomSound-1)
		"
	}
	text
	{
		area 492 198 492 398
		text "SOUND_DESCRIPTION"
		scrollbar 'GUISCRC'
		text style	normal
	}
	button
	{
		area 82 624 300 44
		bam GUIOSTCL
		text "PLAY_SOUND_BUTTON"
		text style "button"
		action "createCharScreen:OnPlayButtonClick()"
	}
	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}
}

`
function hatedRaceOrGeneralHelp()
	race = chargen.hatedRace[currentChargenHatedRace]
	if race then
		return Infinity_FetchString(race.desc)
	else
		return Infinity_FetchString(17256)
	end
end
`
menu
{
	name 'CHARGEN_HATEDRACE'
	align center center
	ignoreesc
	label
	{
		area 0 0 1024 768
		mosaic 'GUICGB'
		enabled "CurrentlyInGame()"
	}
	label
	{
		area 0 159 1024 609
		mosaic GUISMF
	}
	label
	{
		area 18 164 338 44
		text "HATED_RACE_TITLE"
		text style "title"
	}
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 340 44
				text lua "Infinity_FetchString(chargen.hatedRace[rowNumber].name)"
				text style "list"
				pad 8 0 0 0
				
			}
		}
		action "
			if chargen.hatedRace[currentChargenHatedRace] then
				createCharScreen:OnRacialEnemySelectButtonClick(chargen.hatedRace[currentChargenHatedRace].id)
			end
			"
		rowheight 44
		area 24 224 332 382
		table "chargen.hatedRace"
		var currentChargenHatedRace
		scrollbar	'GUISCRC'
	}
	text
	{
		area 414 184 574 412
		text lua "hatedRaceOrGeneralHelp()"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}
`
charNameEdit = ""
`
menu
{
	name 'CHARGEN_NAME'
	modal
	align center center
	ignoreesc
	onopen 
	"
		if chargen.name then
			charNameEdit = chargen.name
		else
			charNameEdit = ''
		end
		Infinity_FocusTextEdit('charNameEditArea')
	"
	label
	{
		area 0 0 406 415
		mosaic 'GUIERR'

	}
	label
	{
		area 66 46 272 44
		text "NAME_LABEL"
		text style "button"
	}
	
	label
	{
		area 72 108 256 34
		fill            112 111 111 64
	}
	edit
	{
		name		"charNameEditArea"
		area		78 114 244 24
		var			charNameEdit
		text style	"edit"
		maxlines	1
		maxchars	20
	}
	button
	{
		on escape
		area 52 216 302 44
		bam GUIOSTCL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu(); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 52 266 302 44
		bam GUIOSTCL
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action "Infinity_PopMenu(); createCharScreen:OnDoneButtonClick()"
	}

}
`
createBioEdit = ""
`
menu
{
	name 'CHARGEN_BIO'
	align center center
	ignoreesc
	label
	{
		area 0 154 1024 614
		mosaic 'GUIMPB'
	}
	label
	{
		area 34 172 968 52
		text "BIOGRAPHY_TITLE"
		text style "title"
	}
	edit
	{
		name		"createBioEditArea"
		area		34 254 944 338
		var			createBioEdit
		scrollbar	'GUISCRC'
		text style	"edit"
	}
	button
	{
		on escape
		area 192 718 232 44
		text "BACK_BUTTON"
		text style "button"
		bam GUIOSTUL
		action "createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		area 438 718 206 44
		text "CLEAR_BUTTON"
		text style "button"
		bam GUIOSTUM
		action "createBioEdit = ''"
	}
	button
	{
		on return
		area 650 718 238 44
		text "DONE_BUTTON"
		text style "button"
		bam GUIOSTUR
		action "createCharScreen:OnDoneButtonClick()"
	}

}
`
list_GUICG_20_2_idx = 0
function NextOrDone()
	if createCharScreen:GetImportState() == 1 then
		return t("NEXT_BUTTON")
	else
		return t("DONE_BUTTON")
	end
end
`
menu
{
	name 'CHARGEN_IMPORT'
	align center center
	ignoreesc
	onOpen
	"
		list_GUICG_20_2_idx = 0
	"
	label
	{
		area 0 156 1024 612
		mosaic 'GUISMDA'
	}
	label
	{
		area 34 172 488 52
		text "IMPORT_TITLE"
		text style "title"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "list_GUICG_20_2[rowNumber]"
				text style "list"
				pad 8 0 0 0
			}
		}
		area 22 244 508 424
		rowheight	34
		table		"list_GUICG_20_2"
		var			"list_GUICG_20_2_idx"
		scrollbar	'GUISCRC'
		action
		"
			Infinity_OnCharacterImportItemSelect(list_GUICG_20_2_idx - 1)
		"
	}
	text
	{
		area 574 190 418 412
		text 10963
		text style normal
		scrollbar 'GUISCRC'
	}
	button
	{
		on escape
		area 192 718 232 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu('CHARGEN_IMPORT'); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text lua "NextOrDone()"
		text style "button"
		clickable lua "list_GUICG_20_2_idx ~= 0"
		action "Infinity_PopMenu('CHARGEN_IMPORT'); createCharScreen:OnDoneButtonClick()"
	}

}

`
chargenExportCharacterEdit = ""
list_GUICG_21_2_idx = 0
`
menu
{
	name 'CHARGEN_EXPORT'
	modal
	align center center
	ignoreesc
	onopen "chargenExportListId = 0"
	label
	{
		area 0 162 1024 606
		mosaic 'GU3MPB'
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "list_GUICG_21_2[rowNumber]"
				text style "list"
				pad 8 0 0 0
			}
		}
		area 22 244 410 360
		rowheight	18
		table		"list_GUICG_21_2"
		var			"chargenExportListId"
		scrollbar	'GUISCRC'
		action
		"
			createCharScreen:OnCharacterExportItemSelect(chargenExportListId - 1)
		"
	}
	text
	{
		area 484 192 506 412
		text 10962
		text style "normal"

	}
	label
	{
		area		82 624 298 23
		text		"EXPORT_FILENAME_LABEL"
		text style	"label"
		text color 3
	}
	edit
	{
		name		"chargenExportCharacterEditArea"
		area		82 642 298 26
		var			chargenExportCharacterEdit
		text style	"edit"
		maxlines	1
	}
	button
	{
		on escape
		area 198 718 234 44
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action "Infinity_PopMenu('CHARGEN_EXPORT'); createCharScreen:OnCancelButtonClick()"
	}
	button
	{
		on return
		area 438 718 206 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style "button"
		action "Infinity_PopMenu('CHARGEN_EXPORT'); createCharScreen:OnDoneButtonClick()"
	}
	
}
menu
{
	name 'CHARGEN_DUALCLASS'
	align center center
	ignoreesc
	label
	{
		area 0 0 864 710
		mosaic guidcx
	}
	label
	{
		area 82 10 700 44
		text "DUALCLASS_TITLE"
		text style "title"
	}
	label
	{
		area 62 124 363 37
		text lua "characters[currentID].name"
		text style "label"
	}
	label
	{
		area 459 124 363 37
		text lua "characters[currentID].class"
		text style "label"
	}
	label
	{
		area 136 191 177 243
		bitmap		lua "characters[currentID].portrait"
	}
	text
	{
		area 481 194 336 407
		text 10811 --dual class info
		text style "normal"
		scrollbar	'GUISCRC'
	}
	button
	{
		area 90 495 303 49
		clickable lua "createCharScreen:GetCurrentStep() == const.STEP_DUALCLASS_CLASS"
		bam GUIOSTCL
		text "CLASS_BUTTON"
		text style "button"
		action
		"
			createCharScreen:OnMenuButtonClick()
		"
	}
	button
	{
		area 90 544 303 49
		clickable lua "createCharScreen:GetCurrentStep() == const.STEP_DUALCLASS_PROFICIENCIES"
		bam GUIOSTCL
		text "SKILLS_BUTTON"
		text style "button"
		action
		"
			createCharScreen:OnMenuButtonClick()
		"
	}
	button
	{
		area 464 653 236 44
		bam GUIOSTUR
		clickable lua "createCharScreen:GetCurrentStep() == const.STEP_DUALCLASS_DONE"
		text "DONE_BUTTON"
		text style "button"
		action
		"
			createCharScreen:OnDoneButtonClick()
		"
	}
	button
	{
		area 210 653 236 44
		clickable false
		bam GUIOSTUL
		text "BACK_BUTTON"
		text style "button"
		action
		"
			createCharScreen:OnCancelButtonClick()
		"
	}
}
`
difficulties = 
{
	{name = "DIFFICULTY_LABEL_STORYMODE", 		description = "DIFFICULTY_DESCRIPTION_STORYMODE_BG2EE"},
	{name = "DIFFICULTY_LABEL_EASY", 			description = "DIFFICULTY_DESCRIPTION_EASY_BG2EE"},
	{name = "DIFFICULTY_LABEL_NORMAL", 			description = "DIFFICULTY_DESCRIPTION_NORMAL_BG2EE"},
	{name = "DIFFICULTY_LABEL_CORERULES", 		description = "DIFFICULTY_DESCRIPTION_CORERULES_BG2EE"},
	{name = "DIFFICULTY_LABEL_HARD", 			description = "DIFFICULTY_DESCRIPTION_HARD_BG2EE"},
	{name = "DIFFICULTY_LABEL_INSANE", 			description = "DIFFICULTY_DESCRIPTION_INSANE_BG2EE"},
	{name = "DIFFICULTY_LABEL_LEGACYOFBHAAL", 	description = "DIFFICULTY_DESCRIPTION_LEGACYOFBHAAL_BG2EE"},
}
fromSinglePlayer = false
fromMultiPlayer = false
function WhoYouGonnaCall()	
	--singleplayer or import
	fromSinglePlayer = (createCharScreen:GetEngineState() == 1 or createCharScreen:GetEngineState() == 7) and multiplayerScreen:GetEngineState() ~= 1
end
`
menu
{
	name 'CHARGEN_DIFFICULTY'
	align center center
	ignoreesc
	onopen 
	"
		currentDifficulty = 3
		WhoYouGonnaCall()
	"
	label
	{
		mosaic GUICREDT
		area 0 0 1024 768
	}
	label
	{
		area 30 6 966 50
		text "DIFFICULTY_LABEL"
		text style "title"
	}
	list
	{
		column 
		{ 
			width 15
			label
			{
				area 20 5 60 60
				bam "GUIDIFFS"
				frame lua "rowNumber-1"
				align center center
			}
		}
		column 
		{ 
			width 15
			label
			{
				area 0 0 64 -1
				text lua "t( difficulties[rowNumber].name )"
				text style "label"
				text align center center
				text color	B
			}
		}
		column 
		{ 
			width 70
			label
			{
				area 10 0 -1 -1
				text lua "t( difficulties[rowNumber].description )"
				text style "label"
				text point	12
				text align left center
				text color	B
			}
		}
		area 44 106 946 516
		rowheight	69
		table		"difficulties"
		var			"currentDifficulty"
		scrollbar	'GUISCRC'
		action
		"
		"
	}
	button
	{
		on escape
		area 276 712 232 44
		bam GUIOSTUL
		text 15416
		text style "button"
		action 
		"
			Infinity_PopMenu()
			if(createCharScreen:GetEngineState() == 7) then
				--if create char is in import mode, kick us back to the start screen.
				e:SelectEngine(startEngine)
			end
		"
	}
	button
	{
		area 530 712 238 44
		bam GUIOSTUR
		text lua "t('VENTURE_FORTH')"
		text style "button"
		enabled "fromSinglePlayer"
		action 
		"
			Infinity_PopMenu()
			createCharScreen:AcceptCharacter(currentDifficulty)
		"
	}
	button
	{
		area 530 712 238 44
		bam GUIOSTUR
		text 11973
		text style "button"
		enabled "fromMultiPlayer"
		action 
		"
			Infinity_PopMenu()
			Infinity_PopMenu()
			Infinity_PopMenu()
			Infinity_PopMenu()

			if connectionLocalNetworkGame == 1 then
				connectionIsHosting = true
				chooseNetworkProtocol(2)
			end

			fromMultiPlayer = false
			mulitplayerPreexistingDifficulty = currentDifficulty
			connectionScreen:OnNewGameButtonClick()
		"
	}
}
`
currentHLASelection = nil
function chargenHLADescription()
	if currentHLASelection == nil then
		return 63817
	else
		return chargen.HLAs[currentHLASelection].description
	end
end
function chargenHLAPlusMinusFrame(cell, rownumber)
	if cell == 3 then
		if chargen.HLAs[rownumber].canAdd then
			return currentCellCheck(cell)
		else
			return 3
		end
	elseif cell == 4 then
		if chargen.HLAs[rownumber].canSubtract then
			return currentCellCheck(cell)
		else
			return 3
		end
	end
end
`
menu
{
	name 'CHARGEN_HIGH_LEVEL_ABILITIES'
	align center center
	ignoreesc
	modal
	onOpen 
	"
		currentHLASelection = nil
	"
	label
	{
		area 0 0 864 710
		mosaic GUIHSBS
	}
	label
	{
		area 74 10 716 52
		text "HIGH_LEVEL_ABILITIES_TITLE"
		text style "title"
	}
	label
	{
		area 36 114 448 52
		text lua "chargen.numHLAs"
		text style "title"
	}
	text
	{
		area 522 118 302 494
		text lua "Infinity_FetchString(chargenHLADescription())"
		text style "normal"
		scrollbar	'GUISCRC'
	}
	
	list
	{
		column
		{
			width 15

			label
			{
				bam GUIBTBUT
				area 0 0 52 52 
				align center center
				icon lua "chargen.HLAs[rowNumber].icon"
				glow lua "chargen.HLAs[rowNumber].count > 0"
				count lua "chargen.HLAs[rowNumber].count"
			}
		}
		column
		{
			width 61
			label
			{
				area 4 0 -1 -1
				text lua "Infinity_FetchString(chargen.HLAs[rowNumber].name)"
				text style "normal"
				align left center
				
			}
		}
		column
		{
			width 12
			label
			{
				area 0 4 45 42
				bam GUIOSW
				frame lua "chargenHLAPlusMinusFrame(3, rowNumber)"
				sequence 0
			}
		}
		column
		{
			width 12
			label
			{
				area 0 4 45 42
				bam GUIOSW
				frame lua "chargenHLAPlusMinusFrame(4, rowNumber)"
				sequence 1

			}
		}


		scrollbar	'GUISCRC'
		rowheight 52
		area 58 194 404 404
		table "chargen.HLAs"
		var currentHLASelection
		action 
		"
			if cellNumber == 3 and chargenHLAPlusMinusFrame(3, currentHLASelection) ~= 3 then
				createCharScreen:OnHLAButtonClick(currentHLASelection, 1)
			elseif cellNumber == 4 and chargenHLAPlusMinusFrame(4, currentHLASelection) ~= 3 then
				createCharScreen:OnHLAButtonClick(currentHLASelection, -1)
			end
			cellNumber = nil
		"
	}
	button
	{
		area 210 652 238 44
		bam GUIOSTUL
		text "DONE_BUTTON"
		text style "button"
		clickable lua "createCharScreen:IsDoneButtonClickable()"
		action 
		"
			createCharScreen:OnDoneButtonClick()
		"
	}
}

`
TEXT_popup_big = 0
`
menu
{
	name 'POPUP_BIG'
	align center center
	modal
	label
	{
		area 0 0 512 651
		mosaic GUICONNB
	}
	text
	{
		area 82 64 338 452
		text lua "Infinity_FetchString(TEXT_popup_big)"
		text style	"label"
		text align left top
		scrollbar 'GUISCRC'
	}
	button
	{
		area 148 530 204 44
		bam GUIOSTUM
		text "DONE_BUTTON"
		text style	"button"
		action 
		"
			Infinity_PopMenu()
		"
	}
}


`
list_GUIMOVIE_0_0_idx = 0
`
menu
{
	name 'MOVIES'
	align center center

	button
	{
		on escape
		action
		"
			--Return to world screen on escape 
			e:SelectEngine(optionsScreen)
		"
	}
	label
	{
		area 0 0 1024 768
		mosaic "GUIMOVB"
	}
	label
	{
		area 318 136 390 44
		text "MOVIES_TITLE"
		text style "title"
	}
	list
	{
		column 
		{ 
			width 100
			label
			{
				area 0 0 384 18
				text lua "list_GUIMOVIE_0_0[rowNumber].description"
				text style	"list"
				text align left center
			}
		}
		area 318 184 390 270
		rowheight	18
		table		"list_GUIMOVIE_0_0"
		var		"list_GUIMOVIE_0_0_idx"
		scrollbar	'GUISCRC'
		action
		"
			moviesScreen:OnMovieItemSelect(list_GUIMOVIE_0_0[list_GUIMOVIE_0_0_idx].movieCode)
		"
	}
	button
	{
		area 366 486 300 44
		bam GUIOSTCL
		text "PLAY_MOVIE_BUTTON"
		text style "button"
		action "moviesScreen:OnPlayButtonClick()"
	}
	button
	{
		area 366 540 300 44
		bam GUIOSTCL
		text "CREDITS_BUTTON"
		text style "button"
		action "moviesScreen:OnCreditsButtonClick()"
	}
	button
	{
		area 418 602 204 44
		bam GUIOSTLM
		text "DONE_BUTTON"
		text style "button"
		action 
		"
			Infinity_PopMenu('MOVIES')
			moviesScreen:OnDoneButtonClick()
		"
	}


}
`
--Multiplayer start.
mp_shownSessions = {}
selectedMp = 0
detailsStr = ""
passwordReq = 0
passwordMp = ""
connectionPlayerNameEdit = ""
connectionFilterNoPasswords = 0
connectionFilterNoFullGames = 0
selectedIndex = 0
connectionIsHosting = false

function connectionBuildGameList()
	local index = 1
	local count = 0
	local entryOK = true
	local foundSelected = false

	for index = 1, #(mp_sessions), 1 do
		entryOK = true
		Infinity_GetPasswordRequired(index)
		if mp_sessions[index] == nil then
			entryOK = false
		elseif mp_sessions[index]["flags"] == nil then
			entryOK = false
		elseif connectionFilterNoPasswords == 1 and passwordReq ~= 0 then
			entryOK = false
		elseif connectionFilterNoFullGames == 1 and mp_sessions[index]["players"] == 6 then 
			entryOK = false
		end

		if entryOK == true then
			count = count + 1
			mp_shownSessions[count] = {}
			mp_shownSessions[count]["actualIndex"] = index
			mp_shownSessions[count]["updated_at"] = mp_sessions[index]["updated_at"]

			if mp_sessions[index]['sessionIDString'] == selectedIndex then
				selectedMp = count
				foundSelected = true
			end
		end
	end

	local tableCount = #(mp_shownSessions) 
	while tableCount > count do
		mp_shownSessions[tableCount] = nil
		tableCount = tableCount - 1
	end

	if foundSelected == false then
		selectedMp = 0
	end
end
function chooseNetworkProtocol(num)
	connectionScreen:SelectServiceProvider(num)
end
function joinGameEnabled()
	if selectedMp <= 0 or mp_shownSessions[selectedMp]['actualIndex'] == nil then
		return 0
	else
		return 1
	end
end
function gameHasPassword(slot)
	if(mp_sessions[mp_shownSessions[slot]["actualIndex"]] == nil) then
		--if the session isn't loaded don't show anything.
		return ""
	end
	Infinity_GetPasswordRequired(mp_shownSessions[slot]["actualIndex"])
	if passwordReq ~= 0 then 
		ret = t("YES")
	else
		ret = t("NO")
	end
	return ret
end
function connectionGetGameName(slot)
	ret = ""

	ret = mp_sessions[mp_shownSessions[slot]["actualIndex"]]['name']

	return ret
end
function connectionGetNumPlayers(slot)
	ret = 0

	ret = mp_sessions[mp_shownSessions[slot]["actualIndex"]]['players']

	return ret
end
function connectionGetGameType(slot)
	ret = ""

	if mp_sessions[mp_shownSessions[slot]["actualIndex"]] ~= nil then
		if mp_sessions[mp_shownSessions[slot]["actualIndex"]]["version"] == "bg2ee-main" then
			ret = t("MAIN_GAME_BG2_LABEL")
		elseif mp_sessions[mp_shownSessions[slot]["actualIndex"]]["version"] == "bg2ee-bp" then
			ret = t("ARENA_MODE_BG2_LABEL")
		elseif mp_sessions[mp_shownSessions[slot]["actualIndex"]]["version"] == "bg2ee-tob" then
			ret = t("EXPANSION_BG2_LABEL")
		end
	end

	return ret
end
function matchMultiplayerGameType(gameVersion)
	if gameVersion == "bg2ee-main" then
		startEngine:OnSoAButtonClick(false)
		e:CheckGUISong()
	elseif gameVersion == "bg2ee-bp" then
		startEngine:OnTBPButtonClick(false)
		e:CheckGUISong()
	elseif gameVersion == "bg2ee-tob" then
		startEngine:OnToBButtonClick(false)
		e:CheckGUISong()
	end
end
`
menu
{
	name 'CONNECTION'
	align center center
	onOpen
	"
		connectionFilterNoPasswords = 0
		connectionFilterNoFullGames = 0
		connectionIsHosting = false
		connectionBuildGameList()

		if connectionPlayerNameEdit == '' then
			connectionSetDefaultGameSettings()
		end
	"
	label -- Background
	{
		area 0 0 1024 768
		mosaic GUIINVHB 
	}
	label -- Title
	{
		area 174 12 700 40
		text  "JOIN_GAME_TITLE"
		text style title
	}
	label
	{
		area 72 196 504 24
		text lua "t('GAME_NAME_LABEL')"
		text style "label_parchment"
		align center center
	}
	label
	{
		area 576 196 84 24
		text lua "t('PASSWORD_LABEL')"
		text style "label_parchment"
		align center center
	}
	label
	{
		area 660 196 70 24
		text lua "t('PLAYERS_LABEL')"
		text style "label_parchment"
		align center center
	}
	label
	{
		area 730 196 186 24
		text lua "t('GAME_TYPE_LABEL')"
		text style "label_parchment"
		align center center
	}
	list -- Multiplayer sessions
	{
		column 
		{ 
			width 60 
			label
			{
				area 20 0 500 40
				text lua "connectionGetGameName(rowNumber)"
				text style	"list_parchment"
				align left center 
			}

		}
		column 
		{ 
			width 10 
			label
			{
				area 20 0 210 40
				text lua "gameHasPassword(rowNumber)"
				text style	"list_parchment"
				align left center 
			}

		}
		column 
		{ 
			width 10 
			label
			{
				area 20 0 210 40
				text lua "connectionGetNumPlayers(rowNumber)"
				text style	"list_parchment"
				align left center 
			}

		}
		column 
		{ 
			width 20 
			label
			{
				area 20 0 210 40
				text lua "connectionGetGameType(rowNumber)"
				text style	"list_parchment"
				align left center 
			}

		}

		area 72 220 882 364
		
		rowheight	44
		table		"mp_shownSessions"
		var			selectedMp
		scrollbar	'GUISCRC'
		action
		"
			selectedIndex = mp_sessions[mp_shownSessions[selectedMp]['actualIndex']]['sessionIDString']
		"
	}

	label -- player name
	{
		area 300 80 210 40
		text  "PLAYER_NAME_LABEL"
		text style "label"
	}
	label
	{
		area 304 120 206 38
		fill 112 111 111 64
	}
	edit
	{
		name		"ConnectionPlayerNameEditArea"
		area		308 125 196 27
		var			connectionPlayerNameEdit
		text style	"edit"
		text align  center center
		maxlines	1
		maxchars 	32
	}

	label -- filter options
	{
		area		559 80 165 45
		text		style 'label'
		text		"CONNECTION_NOT_PASSWORD_PROTECTED_LABEL"
		align 		left center
		tooltip lua "t('CONNECTION_NO_PASSWORDS_TOOLTIP')"
	}
	button
	{
		area		514 80 45 45
		bam 		ROUNDBUT
		glow lua	"connectionFilterNoPasswords"
		align 		center center
		tooltip lua "t('CONNECTION_NO_PASSWORDS_TOOLTIP')"
		action
		"
			connectionFilterNoPasswords = 1 - connectionFilterNoPasswords
			connectionBuildGameList()
		"
	}
	label
	{
		area		559 120 165 44
		text		style 'label'
		text		"CONNECTION_NOT_FULL_LABEL"
		align 		left center
		tooltip lua "t('CONNECTION_NO_FULL_GAMES_TOOLTIP')"
	}
	button
	{
		area		514 120 45 45
		bam 		ROUNDBUT
		glow lua	"connectionFilterNoFullGames"
		align 		center center
		tooltip lua "t('CONNECTION_NO_FULL_GAMES_TOOLTIP')"
		action
		"
			connectionFilterNoFullGames = 1 - connectionFilterNoFullGames
			connectionBuildGameList()
		"
	}

	button -- Create game
	{
		area		62 114 206 44
		bam			GUIOSTUM
		sequence	6
		text  		"CONNECTION_CREATE_NEW_GAME_BUTTON"
		text style	"button"
		action
		"
			Infinity_PushMenu('CONNECTION_CREATE')
		"	
	}
	button -- Direct Connect
	{
		area		418 638 206 44
		bam			GUIOSTUM
		sequence	6
		text  		"CONNECTION_DIRECT_CONNECTION_BUTTON"
		text style	"button"
		tooltip lua "t('CONNECTION_DIRECT_CONNECT_TOOLTIP')"
		action
		"
			connectionIsHosting = false
			chooseNetworkProtocol(2)
		"	
	}
	button -- refresh
	{
		area		894 92 60 60
		bam 		'GUMPBUTX'
		sequence 	2
		align 		center center
		tooltip lua "t('CONNECTION_REFRESH_TOOLTIP')"
		action
		"
			selectedMp = 0
			mp_shownSessions = {}
			mp_sessions = {}
			connectionScreen:ClearSessions()
		"
	}

	button -- Join game
	{
		area		532 714 238 44
		bam			GUIOSTUR
		sequence	6
		text  "JOIN_BUTTON"
		text style	"button"
		clickable lua	"joinGameEnabled()"
		action
		"
			Infinity_GetPasswordRequired(mp_shownSessions[selectedMp]['actualIndex'])
			if string.find(connectionPlayerNameEdit, '%S') == nil then
				Infinity_PushMenu('CONNECTION_NAME')
			elseif passwordReq == 0 then
				Infinity_PopMenu(); 
				Infinity_PopMenu(); 
				mp_sessions[mp_shownSessions[selectedMp]['actualIndex']]['password'] = passwordMp
				Infinity_JoinMultiplayerGame(mp_shownSessions[selectedMp]['actualIndex'])
			else
				Infinity_PushMenu('CONNECTION_PASSWORD')
			end
		"	
	}
	button -- Back/ Log out
	{
		area		278 714 236 44
		bam			GUIOSTUL
		sequence	0
		text  "BACK_BUTTON"
		text style	"button"
		on 			escape
		action
		"
			Infinity_PopMenu();
			connectionScreen:OnMainCancelButtonClick()
		"	
	}
}
`
connectionTCPIPEdit = ""
`
menu
{
	name 'CONNECTION_IP'
	modal
	align center center

	onopen "Infinity_FocusTextEdit('ConnectionTCPIPEditArea')"
	label
	{
		area 0 0 680 242
		mosaic GUIERR6 
	}
	label --Title
	{
		area 38 20 592 64
		text  20681
		text style	"label"
	}
	button
	{
		area		370 170 234 44
		bam		GUIOSTUR
		sequence	0
		text  "DONE_BUTTON"
		text style	"button"
		on		return
		clickable lua "connectionScreen:IsValidAddress(connectionTCPIPEdit)"
		action
		"
			Infinity_PopMenu();
			connectionScreen:JoinGameIPAddress(connectionTCPIPEdit)
		"	
	}
	button
	{
		area		88 170 234 44
		bam		GUIOSTUL
		sequence	1
		text  "CANCEL_BUTTON"
		text style	"button"
		on 		escape
		action
		"
			Infinity_PopMenu();
			chooseNetworkProtocol(1)
		"	
	}
	
	label
	{
		area 56 84 542 32
		fill 112 111 111 64
	}
	
	edit
	{
		name		"ConnectionTCPIPEditArea"
		area		62 88 532 22
		var		connectionTCPIPEdit
		text style	"edit"
		maxlines	1
	}
}
`
connection = {}
connectionSessionNameEdit = ""
connectionSessionPasswordEdit = ""
connectionPasswordProtected = 0
connectionLocalNetworkGame = 0

function connectionCreateGameClickable()
	local ret = string.find(connectionPlayerNameEdit, '%S') ~= nil and string.find(connectionSessionNameEdit, '%S') ~= nil

	if connectionPasswordProtected == 1 then
		ret = ret and string.find(connectionSessionPasswordEdit, '%S') ~= nil
	end

	return ret
end
function connectionSetDefaultGameSettings() 
	local player = t("MULTIPLAYER_DEFAULT_PLAYER")
	local game = t("MULTIPLAYER_ENTER_GAME_NAME")
	local pass = t("MULTIPLAYER_ENTER_GAME_PASSWORD")

	if connectionPlayerNameEdit == "" then
		connectionPlayerNameEdit = Infinity_GetINIString('Multiplayer', 'Player Name', player)
		Infinity_SetINIValue('Multiplayer', 'Player Name', connectionPlayerNameEdit)
	end

	if connectionSessionPasswordEdit == "" then
		connectionSessionPasswordEdit = Infinity_GetINIString('Multiplayer', 'Session Password', pass)
		Infinity_SetINIValue('Multiplayer', 'Session Password', connectionSessionPasswordEdit)
	end

	if connectionSessionNameEdit == "" then
		connectionSessionNameEdit = Infinity_GetINIString('Multiplayer', 'Session Name', game)
		Infinity_SetINIValue('Multiplayer', 'Session Name', connectionSessionNameEdit)
	end

	if connectionSessionPasswordEdit ~= "" then
		connectionPasswordProtected = 1
	else
		connectionPasswordProtected = 0
	end

	if connectionScreen:HasServiceProvider() then
		connectionLocalNetworkGame = 0
	else
		connectionLocalNetworkGame = 1
	end
end
`
menu
{
	name 'CONNECTION_CREATE'
	align center center
	ignoreEsc
	modal

	onOpen
	"
		connectionSetDefaultGameSettings()
	"

	label
	{
		area 0 0 512 651
		mosaic "GUICONNB"
	}
	label
	{
		area		54 6 392 42
		text		style 'title'
		text		"CREATEGAME_TITLE"
	}
	
	label
	{
		area 100 114 298 30
		fill        112 111 111 64
	}
	label -- player
	{
		area		80 69 340 45
		text		style 'label'
		text		"PLAYER_NAME_LABEL"
	}
	edit
	{
		name		"connectionPlayerNameEditArea"
		area		110 118 282 22
		var			connectionPlayerNameEdit
		text 		style "edit"
		maxlines	1
		maxchars 	32
		
	}

	label -- session
	{
		area		80 159 340 45
		text		style 'label'
		text		"SESSION_NAME_LABEL"
	}
	label
	{
		area 100 204 304 30
		fill        112 111 111 64
	}
	edit
	{
		name		"connectionSessionNameEditArea"
		area		110 208 288 22
		var			connectionSessionNameEdit
		text 		style	"edit"
		maxlines	1
	}


	text -- password option
	{
		area		179 259 241 45
		text		style 'label'
		text		"CONNECTION_PASSWORD_PROTECTED"
		tooltip lua "t('CONNECTION_PASSWORD_PROTECTED_TOOLTIP')"
		align 		left center
	}
	button
	{
		area		134 259 45 45
		bam 		ROUNDBUT
		glow lua	"connectionPasswordProtected"
		align 		center center
		tooltip lua "t('CONNECTION_PASSWORD_PROTECTED_TOOLTIP')"
		action
		"
			connectionPasswordProtected = 1 - connectionPasswordProtected
			if connectionPasswordProtected == 1 then
				Infinity_FocusTextEdit('connectionSessionPasswordEditArea')
			end
		"
	}

	text -- local option
	{
		area		179 304 241 45
		text		style 'label'
		text		"CONNECTION_LOCAL_NETWORK_GAME"
		tooltip lua "t('CONNECTION_LOCAL_NETWORK_GAME_TOOLTIP')"
		align 		left center
	}
	button
	{
		area		134 304 45 45
		bam 		ROUNDBUT
		glow lua	"connectionLocalNetworkGame"
		align 		center center
		tooltip lua "t('CONNECTION_LOCAL_NETWORK_GAME_TOOLTIP')"
		action
		"
			if connectionScreen:HasServiceProvider() then
				connectionLocalNetworkGame = 1 - connectionLocalNetworkGame
			end
		"
	}

	label -- password
	{
		area		80 363 340 45
		text		style 'label'
		text		"CHOOSE_PASSWORD_LABEL"
		enabled 	connectionPasswordProtected
	}
	edit
	{
		name		"connectionSessionPasswordEditArea"
		area		80 408 340 45
		var			connectionSessionPasswordEdit
		text 		style "edit"
		text 		align center center
		maxlines	1
		enabled 	connectionPasswordProtected
		fill        112 111 111 64
	}
	button
	{
		clickable lua 	"connectionCreateGameClickable()"
		area			152 530 204 48
		bam				'GUIOSTUM'	
		text style		"button"
		text			"CREATEGAME_BUTTON"
		action		
		"
			local stringStart = string.find(connectionPlayerNameEdit, '%S');
			connectionPlayerNameEdit = string.sub(connectionPlayerNameEdit, stringStart, string.len(connectionPlayerNameEdit))
			stringStart = string.find(connectionSessionNameEdit, '%S');
			connectionSessionNameEdit = string.sub(connectionSessionNameEdit, stringStart, string.len(connectionSessionNameEdit))

			if connectionPasswordProtected == 1 then
				stringStart = string.find(connectionSessionPasswordEdit, '%S');
				connectionSessionPasswordEdit = string.sub(connectionSessionPasswordEdit, stringStart, string.len(connectionSessionPasswordEdit))
			end
	
			if connectionPasswordProtected == 0 then
				connectionSessionPasswordEdit = ''
			end

			Infinity_PushMenu('CONNECTION_NEWORSAVED')
		"
	}
	button
	{
		area		152 578 206 48
		bam			'GUIOSTUM'	
		text style	"button"
		text		"BACK_BUTTON"
		action		
		"
			Infinity_PopMenu()
		"
	}
}
menu
{
	name 'CONNECTION_NEWORSAVED'
	align center center
	modal

	label
	{
		area 0 0 900 234
		mosaic "GUIERR7"
	}
	label
	{
		area		12 7 872 129
		text		style 'label'
		text		"CONNECTION_SELECT_GAME_TYPE_LABEL"
	}

	button
	{
		area		346 164 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"NEW_GAME_BUTTON"
		tooltip lua "t('CONNECTION_NEW_GAME_TOOLTIP')"
		action		
		"
			fromMultiPlayer = true
			Infinity_PushMenu('CHARGEN_DIFFICULTY')
		"
	}
	button
	{
		area		640 164 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"LOAD_BUTTON"
		tooltip lua "t('CONNECTION_LOAD_GAME_TOOLTIP')"
		action		
		"
			Infinity_PopMenu()
			Infinity_PopMenu()
			Infinity_PopMenu()

			if connectionLocalNetworkGame == 1 then
				connectionIsHosting = true
				chooseNetworkProtocol(2)
			end

			connectionScreen:OnLoadGameButtonClick()
		"
	}

	button
	{
		area		54 164 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"BACK_BUTTON"
		action		
		"
			Infinity_PopMenu()
		"
	}
}
`
connectionPasswordPasswordEdit = ""
`
menu
{
	name 'CONNECTION_PASSWORD'
	align center center
	modal
	onOpen
	"
		if mp_sessions[selectedMp]['name'] == Infinity_GetINIString('Multiplayer', 'Session Name', '') then
			connectionPasswordPasswordEdit = Infinity_GetINIString('Multiplayer', 'Session Password', '')
		else
			connectionPasswordPasswordEdit = ''
		end
		Infinity_FocusTextEdit('connectionPasswordPasswordEditArea')
	"

	label
	{
		area 0 0 660 240
		mosaic "GUIERR6"
	}
	label
	{
		area		12 6 632 45
		text		style 'title'
		text		"PASSWORD_REQUIRED_LABEL"
	}
	label
	{
		area		12 51 632 31
		text		style 'label'
		text		"ENTER_PASSWORD_LABEL"
	}

	button
	{
		bam 		GUIOSW
		on esc
		area 		616 0 44 44
		sequence 	2
		action 
		"	
			Infinity_PopMenu()
		"
	}

	edit
	{
		name		"connectionPasswordPasswordEditArea"
		area		12 82 632 50
		var			connectionPasswordPasswordEdit
		text style	"edit"
		text align 	center center
		maxlines	1
		fill        112 111 111 64
		action
		"
			--On return pressed
			if (key_pressed == 13) then
				local stringStart = string.find(connectionNameNameEdit, '%S')
				if stringStart ~= nil then
					local stringStart = string.find(connectionPasswordPasswordEdit, '%S')
					mp_sessions[selectedMp]['password'] = string.sub(connectionPasswordPasswordEdit, stringStart, string.len(connectionPasswordPasswordEdit) )
					Infinity_PopMenu()
					Infinity_JoinMultiplayerGame(mp_shownSessions[selectedMp]['actualIndex'])
				end
				return -1
			end
			return 1
		"
	}

	button
	{
		area 		416 166 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"DONE_BUTTON"
		clickable lua "connectionPasswordPasswordEdit ~='' and string.find(connectionPasswordPasswordEdit, '%S') ~= nil"
		action		
		"
			Infinity_PopMenu(); 
			local stringStart = string.find(connectionPasswordPasswordEdit, '%S')
			mp_sessions[selectedMp]['password'] = string.sub(connectionPasswordPasswordEdit, stringStart, string.len(connectionPasswordPasswordEdit) )
			Infinity_JoinMultiplayerGame(mp_shownSessions[selectedMp]['actualIndex'])
		"
	}

	button
	{
		area 		34 166 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"BACK_BUTTON"
		action		
		"
			Infinity_PopMenu()
		"
	}
}
`
connectionNameNameEdit = ""
`
menu
{
	name 'CONNECTION_NAME'
	align center center
	modal
	onOpen
	"
		connectionNameNameEdit = ''
		Infinity_FocusTextEdit('connectionNameNameEditArea')
	"

	label
	{
		area 0 0 660 240
		mosaic "GUIERR6"
	}
	label
	{
		area		12 16 632 70
		text		style 'title'
		text  		"PLAYER_NAME_LABEL"
	}

	button
	{
		bam 		GUIOSW
		on esc
		area 		616 0 44 44
		sequence 	2
		action 
		"	
			Infinity_PopMenu()
		"
	}

	edit
	{
		name		"connectionNameNameEditArea"
		area		12 82 632 50
		var			connectionNameNameEdit
		text style	"edit"
		text align 	center center
		maxlines	1
		fill        112 111 111 64
		action
		"
			--On return pressed
			if (key_pressed == 13) then
				local stringStart = string.find(connectionNameNameEdit, '%S')
				if stringStart ~= nil then
					connectionPlayerNameEdit = string.sub(connectionNameNameEdit, stringStart, string.len(connectionNameNameEdit) )
					Infinity_PopMenu()

					Infinity_GetPasswordRequired(mp_shownSessions[selectedMp]['actualIndex'])
					if passwordReq == 0 then
						Infinity_PopMenu(); 
						Infinity_PopMenu(); 
						mp_sessions[mp_shownSessions[selectedMp]['actualIndex']]['password'] = passwordMp
						Infinity_JoinMultiplayerGame(mp_shownSessions[selectedMp]['actualIndex'])
					else
						Infinity_PushMenu('CONNECTION_PASSWORD')
					end
				end
				return -1
			end
			return 1
		"
	}

	button
	{
		area 		416 166 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"DONE_BUTTON"
		clickable lua "connectionNameNameEdit ~='' and string.find(connectionNameNameEdit, '%S') ~= nil"
		action		
		"
			Infinity_PopMenu(); 
			local stringStart = string.find(connectionNameNameEdit, '%S')
			connectionPlayerNameEdit = string.sub(connectionNameNameEdit, stringStart, string.len(connectionNameNameEdit) )

			Infinity_GetPasswordRequired(mp_shownSessions[selectedMp]['actualIndex'])
			if passwordReq == 0 then
				Infinity_PopMenu(); 
				Infinity_PopMenu(); 
				mp_sessions[mp_shownSessions[selectedMp]['actualIndex']]['password'] = passwordMp
				Infinity_JoinMultiplayerGame(mp_shownSessions[selectedMp]['actualIndex'])
			else
				Infinity_PushMenu('CONNECTION_PASSWORD')
			end
		"
	}

	button
	{
		area 		34 166 204 44
		bam			'GUIOSTUM'	
		text style	"button"
		text		"BACK_BUTTON"
		action		
		"
			Infinity_PopMenu()
		"
	}
}
menu
{
	name 'CONNECTION_PLAYERNAME'
	align center center
	ignoreEsc
	modal

	onOpen
	"
		connectionPlayerNameEdit = Infinity_GetINIString('Multiplayer', 'Player Name', 'Player Name')
		Infinity_FocusTextEdit('connectionPlayerNameEditArea')
	"
	label
	{
		area 0 0 512 651
		mosaic "GUICONNB"
	}
	label
	{
		area 83 59 338 32
		text style "label"
		text "CURRENT_PLAYERS_LABEL"
	}
	label
	{
		area 83 446 338 32
		text style "label"
		text "PLAYER_NAME_LABEL"
	}

	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 -1 -1
				text lua "connection.currentPlayers[rowNumber].name"
				text style "edit"
				align center center
			}
		}

		action 
		"
		"

		rowheight 50
		area 83 99 338 338
		table "connection.currentPlayers"
		var connectionSelectedPlayer
	}

	edit
	{
		name		"connectionPlayerNameEditArea"
		area		110 479 280 35
		var			connectionPlayerNameEdit
		text style	"edit"
		text align  center center
		maxlines	1
		maxchars 	32
	}
	button
	{
		clickable 	lua "connectionPlayerNameEdit ~= ''"
		area		154 538 204 44
		bam			GUIOSTUM
		sequence	0
		text  		"DONE_BUTTON"
		text style	"button"
		on			return
		action
		"
			Infinity_PopMenu();
			Infinity_PopMenu();
			connectionScreen:SetPlayerName(connectionPlayerNameEdit)
		"	
	}
}

menu
{
	name 'CONNECTION_JOINING'
	modal
	align center center

	label
	{
		area 0 0 657 234
		mosaic GUIERR6 
	}
	label --Title
	{
		area 30 20 600 64
		text  20274
		text style	"label"
	}
	button
	{
		area		222 170 230 44
		bam		GUIBUTMT
		sequence	0
		text  		"CANCEL_BUTTON"
		text style	"button"
		on		escape
		action
		"
			Infinity_PopMenu();
		"	
	}
}
menu
{
	name 'CONNECTION_ERROR'
	modal
	align center center

	label
	{
		area 0 0 410 420
		mosaic GUIERR
	}
	label --Title
	{
		area 60 100 286 64
		text lua "Infinity_FetchString(CONNECTION_ERROR_MESSAGE)"
		text style	"label"
	}
	button
	{
		area		104 320 202 44
		bam			GUIOSTUM
		sequence	0
		text  		"CANCEL_BUTTON"
		text style	"button"
		on		escape
		action
		"
			Infinity_PopMenu();
		"	
	}
}

menu
{
	name 'CONNECTION_WAITING_FOR_PROVIDER'
	modal
	align center center

	label
	{
		area 0 0 682 234
		mosaic GUIERR6
	}
	label --Title
	{
		area 14 8 628 124
		text "CONNECTION_FINDING_DEVICES"
		text style	"label"
	}
	button
	{
		area 		79 170 234 44
		bam			GUIOSTUL
		sequence	0
		text  		"CANCEL_BUTTON"
		text style	"button"
		on			escape
		action
		"
			Infinity_PopMenu('CONNECTION_WAITING_FOR_PROVIDER')
			Infinity_PopMenu('CONNECTION');
			connectionScreen:OnMainCancelButtonClick()
		"	
	}
	button
	{
		area 		343 170 234 44
		bam			GUIOSTUR
		sequence	0
		text  		"CONNECTION_LOCAL_NETWORK_GAME"
		text style	"button"
		on			return
		action
		"
			Infinity_PopMenu('CONNECTION_WAITING_FOR_PROVIDER')
			connectionScreen:StopConnectingToProvider()
		"	
	}
}

menu
{
	name 'CONNECTION_WAITING_FOR_SERVER'
	modal
	align center center

	label
	{
		area 0 0 408 418
		mosaic GUIERR
	}
	label --Title
	{
		area 70 78 258 84
		text "CONNECTION_WAITING_FOR_SERVER"
		text style	"label"
	}
	button
	{
		area		104 320 202 44
		bam			GUIOSTUM
		sequence	0
		text  		"CANCEL_BUTTON"
		text style	"button"
		on		escape
		action
		"
			Infinity_PopMenu('CONNECTION_WAITING_FOR_SERVER')
			connectionScreen:CancelJoinGame();
		"	
	}
}

menu
{
	name 'BACKGROUND'
	align center center
	label
	{
		area 0 0 3840 2160 
		mosaic 'GUIBG'
	}
}

`
multiplayer = {}
mpChatEdit = ""
mpHelpTextString = ""
mpModifyingCharacter = -1
mpErrorText = -1
mpErrorState = -1
text_GUIMP_0_25 = ""
text_GUIMP_0_25_lines = 0
multiplayerInPermission = false
multiplayerInPermissionForPlayer = 0

multiplayerSessionName = ""
multiplayerSaveName = ""
multiplayerChapter = ""
multiplayerTimePlayed = ""
multiplayerDifficultyLabel = ""
multiplayerDifficultyImage = 0
mulitplayerPreexistingDifficulty = 0;

multiplayerLocalPlayerID = 1

multiplayerFromInGame = false

mpaCharacters = 
{
	{ready = false, name = "", class = "", player = 1, portrait = "NOPORTLS", inprogress = false, color = "0xffffff"},
	{ready = false, name = "", class = "", player = 1, portrait = "NOPORTLS", inprogress = false, color = "0xffffff"},
	{ready = false, name = "", class = "", player = 1, portrait = "NOPORTLS", inprogress = false, color = "0xffffff"},
	{ready = false, name = "", class = "", player = 1, portrait = "NOPORTLS", inprogress = false, color = "0xffffff"},
	{ready = false, name = "", class = "", player = 1, portrait = "NOPORTLS", inprogress = false, color = "0xffffff"},
	{ready = false, name = "", class = "", player = 1, portrait = "NOPORTLS", inprogress = false, color = "0xffffff"}
}

mpaPlayers =
{
	{name = "", id = 0, color = "0x7a7aFF"},
	{name = "", id = 0, color = "0xFFAF7A"},
	{name = "", id = 0, color = "0x7aFFa3"},
	{name = "", id = 0, color = "0x57F9FF"},
	{name = "", id = 0, color = "0xF2F188"},
	{name = "", id = 0, color = "0xFE97FF"}
}

function updateMultiplayerPlayerSlot(slot,setting,value)
	if multiplayerLocalPlayerID == 1 and setting == "name" and mpaPlayers[slot][setting] == "" and value ~= "" then
		mpaPlayers[slot][setting] = value
		broadcastPlayerAdded(slot)
	elseif multiplayerLocalPlayerID == 1 and setting == "name" and mpaPlayers[slot][setting] ~= "" and value == "" then
		broadcastPlayerRemoved(slot)
		mpaPlayers[slot][setting] = value
	else
		mpaPlayers[slot][setting] = value
	end
end
function updateMultiplayerCharacterSlot(slot,setting,value)
	if multiplayerLocalPlayerID == 1 and setting == "color" and mpaCharacters[slot][setting] == "0xffffff" and value ~= "0xffffff" then
		mpaCharacters[slot][setting] = value
		broadcastCharacterAdded(slot)
	elseif multiplayerLocalPlayerID == 1 and setting == "ready" and mpaCharacters[slot][setting] == false and value == true then
		broadcastCharacterReady(slot)
		mpaCharacters[slot][setting] = value
	elseif multiplayerLocalPlayerID == 1 and setting == "ready" and mpaCharacters[slot][setting] == true and value == false then
		broadcastCharacterNotReady(slot)
		mpaCharacters[slot][setting] = value
	else
		mpaCharacters[slot][setting] = value
	end
end

function clearCharacterSlot(slot, announce)
	if announce == true and mpaCharacters[slot]['name'] ~= "" then
		broadcastCharacterRemoved(slot)
	end
	mpaCharacters[slot]['ready'] = false
	mpaCharacters[slot]['name'] = ""
	mpaCharacters[slot]['class'] = ""
	mpaCharacters[slot]['portrait'] = "NOPORTLS"
	mpaCharacters[slot]['inprogress'] = false
	mpaCharacters[slot]['color'] = "0xffffff"
end

function clearPlayerSlot(slot, announce)
	if announce == true and mpaPlayers[slot]["name"] ~= "" then
		broadcastPlayerRemoved(slot)
	end
	mpaPlayers[slot]["name"] = ""
	mpaPlayers[slot]["id"] = 0
end

function getMultiplayerCharacterName(slot, newLine, getClass)
	local ret = ""
	local separator = ", "

	if newLine == true then
		separator = "\n"
	end

	if mpaCharacters[slot]["name"] == "" and multiplayerLocalPlayerID == mpaCharacters[slot]["player"] then
		ret = t("MULTIPLAYER_CREATE_CHARACTER_MESSAGE")
	elseif mpaCharacters[slot]["name"] == "" and multiplayerLocalPlayerID ~= mpaCharacters[slot]["player"] and mpaCharacters[slot]["inprogress"] == false then
		ret = t("MULTIPLAYER_EMPTY_CHARACTER_MESSAGE")
	elseif mpaCharacters[slot]["inprogress"] == true and mpaCharacters[slot]["class"] == "" then
		setStringTokenLua("<PLAYER_NAME_1>",getMultiplayerPlayerName(mpaCharacters[slot]["player"], false, true))
		setStringTokenLua("<SEPERATOR>",separator)
		ret = t("MULTIPLAYER_CREATING_CHARACTER_MESSAGE")
		removeStringTokenLua("<SEPERATOR>")
		removeStringTokenLua("<PLAYER_NAME_1>")
	elseif mpaCharacters[slot]["name"] ~= "" and mpaCharacters[slot]["class"] ~= "" then
		ret = "^0xff"..mpaCharacters[slot]["color"]..mpaCharacters[slot]["name"].."^-"
		if getClass == true then
			ret = ret..separator..mpaCharacters[slot]["class"]
		end
	end

	return ret
end
function getMultiplayerCharacterButtonText(slot)
	local ret = ""

	if mpaCharacters[slot]["name"] == "" and multiplayerLocalPlayerID == mpaCharacters[slot]["player"] then
		ret = t("CREATE_CHAR_BUTTON")
	elseif mpaCharacters[slot]["name"] == "" and multiplayerLocalPlayerID ~= mpaCharacters[slot]["player"] then
		ret = ""
	elseif mpaCharacters[slot]["name"] ~= "" and mpaCharacters[slot]["class"] == "" then
		ret = ""
	elseif mpaCharacters[slot]["name"] ~= "" and mpaCharacters[slot]["class"] ~= "" and mpaCharacters[slot]["player"] ~= multiplayerLocalPlayerID then
		ret = t("MULTIPLAYER_VIEW_DETAILS_BUTTON")
	elseif mpaCharacters[slot]["name"] ~= "" and mpaCharacters[slot]["class"] ~= "" and mpaCharacters[slot]["player"] == multiplayerLocalPlayerID and multiplayer.allowreformparty == false and multiplayerDifficultyLabel ~= "" then
		ret = t("MULTIPLAYER_VIEW_DETAILS_BUTTON")
	elseif mpaCharacters[slot]["name"] ~= "" and mpaCharacters[slot]["class"] ~= "" and mpaCharacters[slot]["player"] == multiplayerLocalPlayerID then
		ret = t("MULTIPLAYER_EDIT_CHAR_BUTTON")
	end

	return ret
end
function shouldGreyscaleEditButton(slot)
	local ret = false
	local storedString = t("MULTIPLAYER_VIEW_DETAILS_BUTTON")

	if multiplayerFromInGame == true then
		ret = true
	end

	if ret == true and getMultiplayerCharacterButtonText(slot) == storedString  then
		ret = false
	end

	if ret == true and (multiplayerLocalPlayerID == 1 or multiplayer.player[multiplayerLocalPlayerID].permissions[7] == true) then
		ret = false
	end

	if ret == true and mpaCharacters[slot]["name"] == "" then
		ret = false
	end

	if ret == false and mpaCharacters[slot]['ready'] == true and getMultiplayerCharacterButtonText(slot) ~= storedString and multiplayerFromInGame == false then
		ret = true
	end

	return ret
end
function getMultiplayerCharacterReadyText(slot)
	local ret = ""

	if mpaCharacters[slot]["name"] == "" and mpaCharacters[slot]["inprogress"] == false then
		ret = ""
	elseif mpaCharacters[slot]["ready"] == false then
		ret = t("MULTIPLAYER_NOT_READY_MESSAGE")
	elseif mpaCharacters[slot]["ready"] == true then
		ret = t("MULTIPLAYER_READY_MESSAGE")
	end

	return ret
end
function getMultiplayerPlayerName(slot,newLine,hostyou)
	local ret = mpaPlayers[slot]["name"]
	if ret ~= "" then
		ret = "^0x"..mpaPlayers[slot]["color"]..mpaPlayers[slot]["name"].."^-"
	end

	local separator = " "
	if newLine == true then
		separator = "\n"
	end

	if hostyou == true then
		if slot == multiplayerLocalPlayerID then
			ret = ret..separator.."^0xFFFFFFFF"..t("MULTIPLAYER_PLAYER_YOU").."^-"
		elseif slot == 1 then
			ret = ret..separator.."^0xFFFFFFFF"..t("MULTIPLAYER_PLAYER_HOST").."^-"
		elseif ret == "" then
			ret = "^0xFF9B9B9B"..t("MULTIPLAYER_EMPTY_PLAYER").."^-"
		end
	end

	return ret
end
function getMultiplayerPlayerControlledCharacter(player,slot)
	local count = 0
	local ret = "NOCTRL" -- need blank square or something

	local index = 1
	for index = 1, 6, 1 do
		if mpaCharacters[index]["player"] == player then
			count = count + 1
		end

		if currentMultiplayerSelectPlayer == player and mpDraggedCharacter == index then
			slot = slot + 1
		end

		if count == slot then
			ret = mpaCharacters[index]["portrait"]
			break
		end
	end

	return ret
end
function getMultiplayerPlayerControlledCharacterSlot(player,slot)
	local count = 0
	local ret = -1

	local index = 1
	for index = 1, 6, 1 do
		if mpaCharacters[index]["player"] == player then
			count = count + 1
		end

		if count == slot then
			ret = index
			break
		end
	end

	return ret
end

function getPlayerKickWidth(slot)
	if multiplayerLocalPlayerID ~= 1 or slot == 1 then
		return 0
	else
		return 10
	end
end

function getPlayerNameWidth(slot)
	if multiplayerLocalPlayerID ~= 1 or slot == 1 then
		return 45
	else
		return 35
	end
end

function getStartGameButtonTooltip()
	if multiplayer.donebuttonclickable then
		return ""
	else
		return t("MULTIPLAYER_CANNOT_START")
	end
end

function updateMultiplayerSessionData(sessionName, saveName, chapter, timePlayed, difficulty)
	local gold = "^0xffc7f8fb"
	multiplayerSessionName = gold..sessionName.."^-"

	if areaName ~= "" then
		multiplayerSaveName = gold..t("MULTIPLAYER_SAVED_GAME_LABEL").."^- ^0xffffffff"..saveName.."^-"
		multiplayerChapter = gold..t("MULTIPLAYER_CHAPTER_LABEL").."^- ^0xffffffff"..chapter.."^-"
		multiplayerTimePlayed = gold..t("MULTIPLAYER_TIME_PLAYED_LABEL").."^- ^0xffffffff"..timePlayed.."^-"
		if difficulty > 0 then
			mulitplayerPreexistingDifficulty = difficulty
			multiplayerDifficultyLabel = gold..t("MULTIPLAYER_DIFFICULTY_LABEL").."^-^0xffffffff"..t(difficulties[difficulty].name).."^-"
			multiplayerDifficultyImage = difficulty - 1
		end
	else
		multiplayerSaveName = gold..t("MULTIPLAYER_NEW_GAME_LABEL").."^- ^0xffffffff"..saveName.."^-"
		multiplayerChapter = gold..t("MULTIPLAYER_CHAPTER_LABEL").."^- ^0xffffffff"..chapter.."^-"
		multiplayerTimePlayed = gold..t("MULTIPLAYER_TIME_PLAYED_NEW_GAME").."^-"
		if difficulty > 0 then
			multiplayerDifficultyLabel = gold..t("MULTIPLAYER_DIFFICULTY_LABEL").."^- ^0xffffffff"..t(difficulties[difficulty].name).."^-"
			multiplayerDifficultyImage = difficulty - 1
		end
	end
end

function broadcastCharacterControlChange(slot, newPlayer)
	if mpaCharacters[slot]["player"] ~= newPlayer then
		local host = getMultiplayerPlayerName(1,false,false)
		local player = getMultiplayerPlayerName(newPlayer,false,false)
		setStringTokenLua("<PLAYER_NAME_1>",host)
		setStringTokenLua("<PLAYER_NAME_2>",player)
		local message = t("MULTIPLAYER_SLOT_"..slot.."_ASSIGNED_TO")
		removeStringTokenLua("<PLAYER_NAME_1>")
		removeStringTokenLua("<PLAYER_NAME_2>")
		Infinity_SendChatMessage(message, true) 
	end
end

function broadcastCharacterAdded(slot)
	local player = getMultiplayerPlayerName(mpaCharacters[slot]["player"],false,false)
	local character = getMultiplayerCharacterName(slot, false, true)
	setStringTokenLua("<PLAYER_NAME_1>",player)
	setStringTokenLua("<CHARACTER_NAME_1>",character)
	local message = t("MULTIPLAYER_HAS_ADDED")
	removeStringTokenLua("<PLAYER_NAME_1>")
	removeStringTokenLua("<CHARACTER_NAME_1>")
	Infinity_SendChatMessage(message, true) 
end

function broadcastCharacterRemoved(slot)
	local player = getMultiplayerPlayerName(mpaCharacters[slot]["player"],false,false)
	local character = getMultiplayerCharacterName(slot, false, true)
	setStringTokenLua("<PLAYER_NAME_1>",player)
	setStringTokenLua("<CHARACTER_NAME_1>",character)
	local message = t("MULTIPLAYER_HAS_REMOVED")
	removeStringTokenLua("<PLAYER_NAME_1>")
	removeStringTokenLua("<CHARACTER_NAME_1>")
	Infinity_SendChatMessage(message, true) 
end

function broadcastCharacterReady(slot)
	local character = getMultiplayerCharacterName(slot, false, false)
	setStringTokenLua("<CHARACTER_NAME_1>",character)
	local message = t("MULTIPLAYER_IS_READY_TO_START")
	removeStringTokenLua("<CHARACTER_NAME_1>")
	Infinity_SendChatMessage(message, true) 
end

function broadcastCharacterNotReady(slot)
	local character = getMultiplayerCharacterName(slot, false, false)
	setStringTokenLua("<CHARACTER_NAME_1>",character)
	local message = t("MULTIPLAYER_IS_NO_LONGER_READY")
	removeStringTokenLua("<CHARACTER_NAME_1>")
	Infinity_SendChatMessage(message, true) 
end

function broadcastPlayerAdded(slot)
	local player = getMultiplayerPlayerName(slot,false,false)
	setStringTokenLua("<PLAYER_NAME_1>",player)
	local message = t("MULTIPLAYER_HAS_JOINED_THE_GAME")
	removeStringTokenLua("<PLAYER_NAME_1>")
	Infinity_SendChatMessage(message, true) 
end

function broadcastPlayerRemoved(slot)
	local player = getMultiplayerPlayerName(slot,false,false)
	setStringTokenLua("<PLAYER_NAME_1>",player)
	local message = t("MULTIPLAYER_HAS_LEFT_THE_GAME")
	removeStringTokenLua("<PLAYER_NAME_1>")
	Infinity_SendChatMessage(message, true) 
end

mpDraggedCharacter = nil
mpDraggedPortrait = 'NOCTRL'

function multiplayerStartSwapPortraits(player, character)
	if multiplayerLocalPlayerID == 1 and player > 0 and player < 7 and mpaPlayers[player]["name"] ~= "" then
		mpDraggedCharacter = character
		multiplayerScreen:SetModifiedCharacterSlot(character - 1)
		currentMultiplayerSelectPlayer = player
		mpDraggedPortrait = mpaCharacters[character]["portrait"]
	end
end

function multiplayerStopSwapPortraits(player)
	if multiplayerLocalPlayerID == 1 then
		if player > 0 and player < 7 and mpaPlayers[player]["name"] ~= "" and currentMultiplayerSelectPlayer ~= nil then
			if mpaCharacters[mpDraggedCharacter]['ready'] == true and mpaCharacters[mpDraggedCharacter]['player'] ~= player then 
				multiplayerScreen:OnReadyButtonClick(mpDraggedCharacter-1)
			end
			broadcastCharacterControlChange(mpDraggedCharacter, player)
			multiplayerScreen:OnPlayerSelection(player-1)
		end
		mpDraggedCharacter = nil
		currentMultiplayerSelectPlayer = nil
		mpDraggedPortrait = 'NOCTRL'
	end
end

function getMultiplayerReadyTooltip(character)
	local ret = ""

	if mpaCharacters[character]["ready"] == true then
		ret = t("MULTIPLAYER_READY_BUTTON_ON_TOOLTIP")
	else
		ret = t("MULTIPLAYER_READY_BUTTON_OFF_TOOLTIP")
	end

	return ret
end

function multiplayerUpdateDraggedPortrait()
	if mpDraggedPortrait ~= 'NOCTRL' and multiplayerLocalPlayerID == 1 then
		local x,y,w,h = Infinity_GetArea('multiplayerDraggingPortraitImage')
		x,y = Infinity_GetMousePosition();
		x = x - 20
		y = y - 30
		Infinity_SetArea('multiplayerDraggingPortraitImage',x,y,w,h)
		return true
	else
		local x,y,w,h = Infinity_GetArea('multiplayerDraggingPortraitImage')
		Infinity_SetArea('multiplayerDraggingPortraitImage',-20,-20,w,h)
		return false
	end
end

function get4CheckFrame(slot)
	local ret = 1

	if mpaCharacters[slot]['ready'] == true and mpaCharacters[slot]['player'] == multiplayerLocalPlayerID then
		ret = 0
	elseif mpaCharacters[slot]['ready'] == true then
		ret = 2
	end

	return ret
end

`
menu
{
	name 'MULTIPLAYER'
	align center center
	ignoreesc
	onOpen
	"
		existingDifficulty = Infinity_GetOption(12, 8) + 1;
		multiplayerFromInGame = multiplayerScreen:GetEngineState() == 2
	"
	label 
	{
		mosaic 'GUICREDT'
		area 0 0 1024 768
	}
	label
	{
		area 162 16 700 44
		text "ARBITRATION_TITLE"
		text style "title"
	}

	label
	{
		area 514 70 492 618
		fill 0 0 0 255
	}
	label
	{
		area 504 60 512 638
		rectangle 3
	}

	label
	{
		area 524 112 471 93
		fill 100 25 25 180
	}
	label
	{
		area 524 207 471 93
		fill 50 50 50 180
	}
	label
	{
		area 524 302 471 93
		fill 100 25 25 180
	}
	label
	{
		area 524 397 471 93
		fill 50 50 50 180
	}
	label
	{
		area 524 492 471 93
		fill 100 25 25 180
	}
	label
	{
		area 524 587 471 93
		fill 50 50 50 180
	}

	label
	{
		area 524 84 136 22
		text lua "t('PLAYER_LABEL')"
		text style "label"
		align center center
	}
	label
	{
		area 660 84 232 22
		text lua "t('CHARACTER_LABEL')"
		text style "label"
		align center center
	}
	label
	{
		area 892 84 103 22
		text lua "t('READY_TO_PLAY_LABEL')"
		text style "label"
		align center center
	}
	list -- character list
	{
		column --player
		{ 
			width 32 
			label
			{
				area 		7 5 140 44
				text lua	"getMultiplayerPlayerName(mpaCharacters[rowNumber]['player'],true,true)"
				text style 	"label"
				enabled 	"multiplayerLocalPlayerID == 1 and rowNumber ~= 1"
			}
			label
			{
				area 		7 0 140 95
				text lua	"getMultiplayerPlayerName(mpaCharacters[rowNumber]['player'],true,true)"
				text style 	"label"
				enabled 	"multiplayerLocalPlayerID ~= 1 or rowNumber == 1"
			}
			label
			{
				area		7 50 140 40
				bam 		'GUIOSTSM'
				sequence 	1
				frame lua 	"currentCellCheck(1)"
				align 		center center
				enabled 	"multiplayerLocalPlayerID == 1 and rowNumber ~= 1"
				text lua	"t('MULTIPLAYER_CHANGE_PLAYER_BUTTON')"
				text style 	"button"
			}

		}
		column --portrait
		{
			width 15
			label
			{
				area		0 0 -1 -1
				bam 		'GUIRSP10'
				sequence 	1
				align 		center center
			}
			label
			{
				area		6 5 56 85
				bitmap lua	'mpaCharacters[rowNumber]["portrait"]'
				sequence 	1
				align 		center center
			}
		}
		column --character
		{ 
			width 45 
			label
			{
				area 		4 0 195 44
				text lua 	"getMultiplayerCharacterName(rowNumber, true, true)"
				text style 	"label"
				enabled 	"getMultiplayerCharacterButtonText(rowNumber) ~= ''"
			}
			label
			{
				area 		4 0 195 95
				text lua 	"getMultiplayerCharacterName(rowNumber, true, true)"
				text style 	"label"
				enabled 	"getMultiplayerCharacterButtonText(rowNumber) == ''"
			}
			label
			{
				area		8 45 195 44
				bam 		'GUIOSTUM'
				sequence 	1
				frame lua 	"currentCellCheck(3)"
				align 		center center
				enabled 	"getMultiplayerCharacterButtonText(rowNumber) ~= ''"
			}
			label
			{
				area		8 45 195 44
				text lua 	"getMultiplayerCharacterButtonText(rowNumber)"
				text style 	"button"
			}
			label
			{
				area		8 45 195 44
				fill 		0 0 0 170
				enabled 	"shouldGreyscaleEditButton(rowNumber)"
			}

		}
		column --ready
		{ 
			width 13 
			label
			{
				area 		0 50 50 44
				text lua	"getMultiplayerCharacterReadyText(rowNumber)"
				text style 	"label"
			}

		}

		area 				520 112 475 570
		
		rowheight			95
		table				"mpaCharacters"
		var					selectedCharacter
		scrollbar			'GUISCRC'
		hidehighlight
		action
		"
			if cellNumber == 1 then
				cellNumber = nil
				if multiplayerLocalPlayerID == 1 and selectedCharacter ~= 1 then
					if multiplayerFromInGame == false then
						multiplayerScreen:SetModifiedCharacterSlot(selectedCharacter - 1)
						currentMultiplayerSelectPlayer = mpaCharacters[selectedCharacter]['player']
						Infinity_PushMenu('MP_PICKPLAYER')
					elseif shouldGreyscaleEditButton(selectedCharacter) == false then
						multiplayerScreen:OnModifyButtonClick()
					end
				end
			elseif cellNumber == 2 then
				cellNumber = nil
			elseif cellNumber == 3 then
				cellNumber = nil
				if shouldGreyscaleEditButton(selectedCharacter) == false then
					if getMultiplayerCharacterButtonText(selectedCharacter) == t('MULTIPLAYER_VIEW_DETAILS_BUTTON') then
						multiplayerScreen:OnPortraitButtonClick(selectedCharacter-1)
					elseif getMultiplayerCharacterButtonText(selectedCharacter) == t('CREATE_CHAR_BUTTON') then
						if multiplayerFromInGame == false then
							multiplayerScreen:SetModifiedCharacterSlot(selectedCharacter-1)
							multiplayerScreen:UpdateModifyCharacterPanel()
						elseif shouldGreyscaleEditButton(selectedCharacter) == false then
							multiplayerScreen:OnModifyButtonClick()
						end
					elseif getMultiplayerCharacterButtonText(selectedCharacter) == t('MULTIPLAYER_EDIT_CHAR_BUTTON') then
						if multiplayerFromInGame == false then
							mpModifyingCharacter = selectedCharacter - 1
							Infinity_PushMenu('MP_MODIFYCHARACTER')
						elseif shouldGreyscaleEditButton(selectedCharacter) == false then
							multiplayerScreen:OnModifyButtonClick()
						end
					end
				end
			elseif cellNumber == 4 then
				cellNumber = nil
			end
		"
		actionAlt
		"
			cellNumber = nil
		"
	}

	--ready buttons
	button
	{
		area 942 112 50 50
		bam 		'4CHECK'
		sequence lua "get4CheckFrame(1)"
		align 		center center
		tooltip lua "getMultiplayerReadyTooltip(1)"
		action
		"
			if multiplayerFromInGame == false then
				if multiplayerLocalPlayerID == mpaCharacters[1]['player'] then
					multiplayerScreen:OnReadyButtonClick(1-1)
				end
			end
		"
	}
	button
	{
		area 942 207 50 50
		bam 		'4CHECK'
		sequence lua "get4CheckFrame(2)"
		align 		center center
		action
		"
			if multiplayerFromInGame == false then
				if multiplayerLocalPlayerID == mpaCharacters[2]['player'] then
					multiplayerScreen:OnReadyButtonClick(2-1)
				end
			end
		"
	}
	button
	{
		area 942 302 50 50
		bam 		'4CHECK'
		sequence lua "get4CheckFrame(3)"
		align 		center center
		action
		"
			if multiplayerFromInGame == false then
				if multiplayerLocalPlayerID == mpaCharacters[3]['player'] then
					multiplayerScreen:OnReadyButtonClick(3-1)
				end
			end
		"
	}
	button
	{
		area 942 397 50 50
		bam 		'4CHECK'
		sequence lua "get4CheckFrame(4)"
		align 		center center
		action
		"
			if multiplayerFromInGame == false then
				if multiplayerLocalPlayerID == mpaCharacters[4]['player'] then
					multiplayerScreen:OnReadyButtonClick(4-1)
				end
			end
		"
	}
	button
	{
		area 942 492 50 50
		bam 		'4CHECK'
		sequence lua "get4CheckFrame(5)"
		align 		center center
		action
		"
			if multiplayerFromInGame == false then
				if multiplayerLocalPlayerID == mpaCharacters[5]['player'] then
					multiplayerScreen:OnReadyButtonClick(5-1)
				end
			end
		"
	}
	button
	{
		area 942 587 50 50
		bam 		'4CHECK'
		sequence lua "get4CheckFrame(6)"
		align 		center center
		action
		"
			if multiplayerFromInGame == false then
				if multiplayerLocalPlayerID == mpaCharacters[6]['player'] then
					multiplayerScreen:OnReadyButtonClick(6-1)
				end
			end
		"
	}

	label
	{
		area 40 308 454 25
		fill 125 125 125 180
	}
	label
	{
		area 40 343 454 47
		fill 50 50 50 180
	}
	label
	{
		area 40 394 454 47
		fill 50 50 50 180
	}
	label
	{
		area 40 445 454 47
		fill 50 50 50 180
	}
	label
	{
		area 40 496 454 47
		fill 50 50 50 180
	}
	label
	{
		area 40 547 454 47
		fill 50 50 50 180
	}
	label
	{
		area 40 598 454 47
		fill 50 50 50 180
	}
	label
	{
		area 40 308 207 25
		text lua "t('PLAYERS_LABEL')"
		text style "label"
		align center center
	}
	label
	{
		area 247 308 187 25
		text lua "t('PARTY_SLOTS_LABEL')"
		text style "label"
		align center center
	}
	label
	{
		area 434 308 60 25
		text lua "t('RULES_LABEL')"
		text style "label"
		align center center
	}
	list -- player list
	{
		column -- kick
		{
			width lua "getPlayerKickWidth(rowNumber)"
			label
			{
				area		6 5 45 45
			}
		}
		column --player
		{ 
			width lua "getPlayerNameWidth(rowNumber)"
			label
			{
				area 		0 0 195 55
				text lua	"getMultiplayerPlayerName(rowNumber, false, true)"
				text style 	"label"
				align 		left center
				enabled 	"getPlayerKickWidth(rowNumber) == 0"
			}
			label
			{
				area 		0 0 150 55
				text lua	"getMultiplayerPlayerName(rowNumber, false, true)"
				text style 	"label"
				align 		left center
				enabled 	"getPlayerKickWidth(rowNumber) ~= 0"
			}

		}
		column --portraits
		{ 
			width 45 
			label
			{
				area		6 5 25 38
			}
		}
		column -- permissions
		{
			width 10
			label
			{
				area		6 5 45 45
			}
		}

		area 				52 339 442 306
		
		rowheight			51
		table				"mpaPlayers"
		var					selectedPlayer
		scrollbar			'GUISCRC'
		hidehighlight
		action
		"
			if cellNumber == 1 and selectedPlayer > 1 then
				cellNumber = 0
			elseif cellNumber == 2 then
				cellNumber = 0
			elseif cellNumber == 3 then
				cellNumber = 0
			elseif cellNumber == 4 and selectedPlayer > 1  then
				cellNumber = 0
			end
		"
	}

	--kick
	button
	{
		area		40 395 46 45
		bam 			GUMPBUTX
		sequence 		4
		clickable lua	"mpaPlayers[2]['name'] ~= ''"
		align 		center center
		enabled 	"multiplayerLocalPlayerID == 1"
		tooltip lua	"t('MULTIPALYER_KICK_TOOLTIP')"
		action
		"
			if mpaPlayers[2]['name'] ~= '' then
				multiplayerScreen:OnKickPlayerButtonClick(2-1)
			end
		"
	}
	button
	{
		area		40 446 46 45
		bam 			GUMPBUTX
		sequence 		4
		clickable lua	"mpaPlayers[3]['name'] ~= ''"
		align 		center center
		enabled 	"multiplayerLocalPlayerID == 1"
		tooltip lua	"t('MULTIPALYER_KICK_TOOLTIP')"
		action
		"
			if mpaPlayers[3]['name'] ~= '' then
				multiplayerScreen:OnKickPlayerButtonClick(3-1)
			end
		"
	}
	button
	{
		area		40 497 46 45
		bam 			GUMPBUTX
		sequence 		4
		clickable lua	"mpaPlayers[4]['name'] ~= ''"
		align 		center center
		enabled 	"multiplayerLocalPlayerID == 1"
		tooltip lua	"t('MULTIPALYER_KICK_TOOLTIP')"
		action
		"
			if mpaPlayers[4]['name'] ~= '' then
				multiplayerScreen:OnKickPlayerButtonClick(4-1)
			end
		"
	}
	button
	{
		area		40 548 46 45
		bam 			GUMPBUTX
		sequence 		4
		clickable lua	"mpaPlayers[5]['name'] ~= ''"
		align 		center center
		enabled 	"multiplayerLocalPlayerID == 1"
		tooltip lua	"t('MULTIPALYER_KICK_TOOLTIP')"
		action
		"
			if mpaPlayers[5]['name'] ~= '' then
				multiplayerScreen:OnKickPlayerButtonClick(5-1)
			end
		"
	}
	button
	{
		area		40 599 46 45
		bam 			GUMPBUTX
		sequence 		4
		clickable lua	"mpaPlayers[6]['name'] ~= ''"
		align 		center center
		enabled 	"multiplayerLocalPlayerID == 1"
		tooltip lua	"t('MULTIPALYER_KICK_TOOLTIP')"
		action
		"
			if mpaPlayers[6]['name'] ~= '' then
				multiplayerScreen:OnKickPlayerButtonClick(6-1)
			end
		"
	}

	--permissions
	button
	{
		area		446 395 46 45
		bam 			GUMPBUTX
		sequence 		3
		clickable lua	"mpaPlayers[2]['name'] ~= '' and multiplayerLocalPlayerID == 1"
		align 		center center
		tooltip lua	"t('MULTIPALYER_PERMISSION_TOOLTIP')"
		action
		"
			if mpaPlayers[2]['name'] ~= '' then
				multiplayerInPermission = true
				multiplayerInPermissionForPlayer = 2
				Infinity_PushMenu('MP_PERMISSIONS')
			end
		"
	}
	button
	{
		area		446 446 46 45
		bam 			GUMPBUTX
		sequence 		3
		clickable lua	"mpaPlayers[3]['name'] ~= '' and multiplayerLocalPlayerID == 1"
		align 		center center
		tooltip lua	"t('MULTIPALYER_PERMISSION_TOOLTIP')"
		action
		"
			if mpaPlayers[3]['name'] ~= '' then
				multiplayerInPermission = true
				multiplayerInPermissionForPlayer = 3
				Infinity_PushMenu('MP_PERMISSIONS')
			end
		"
	}
	button
	{
		area		446 497 46 45
		bam 			GUMPBUTX
		sequence 		3
		clickable lua	"mpaPlayers[4]['name'] ~= '' and multiplayerLocalPlayerID == 1"
		align 		center center
		tooltip lua	"t('MULTIPALYER_PERMISSION_TOOLTIP')"
		action
		"
			if mpaPlayers[4]['name'] ~= '' then
				multiplayerInPermission = true
				multiplayerInPermissionForPlayer = 4
				Infinity_PushMenu('MP_PERMISSIONS')
			end
		"
	}
	button
	{
		area		446 548 46 45
		bam 			GUMPBUTX
		sequence 		3
		clickable lua	"mpaPlayers[5]['name'] ~= '' and multiplayerLocalPlayerID == 1"
		align 		center center
		tooltip lua	"t('MULTIPALYER_PERMISSION_TOOLTIP')"
		action
		"
			if mpaPlayers[5]['name'] ~= '' then
				multiplayerInPermission = true
				multiplayerInPermissionForPlayer = 5
				Infinity_PushMenu('MP_PERMISSIONS')
			end
		"
	}
	button
	{
		area		446 599 46 45
		bam 			GUMPBUTX
		sequence 		3
		clickable lua	"mpaPlayers[6]['name'] ~= '' and multiplayerLocalPlayerID == 1"
		align 		center center
		tooltip lua	"t('MULTIPALYER_PERMISSION_TOOLTIP')"
		action
		"
			if mpaPlayers[6]['name'] ~= '' then
				multiplayerInPermission = true
				multiplayerInPermissionForPlayer = 6
				Infinity_PushMenu('MP_PERMISSIONS')
			end
		"
	}

	--character drag/drop
	--player 1
	button
	{
		area 247 348 180 38
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(1)
		"
	}
	button
	{
		area 				247 348 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(1,1)'
		sequence 			1
		align 				center center
		--No changing control of character 1
	}
	button
	{
		area 				278 348 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(1,2)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			if multiplayerFromInGame == false then
				local slot = getMultiplayerPlayerControlledCharacterSlot(1,2)
				multiplayerStartSwapPortraits(1,slot)
			elseif multiplayerLocalPlayerID == 1 or multiplayer.player[multiplayerLocalPlayerID].permissions[1] == true then
				multiplayerScreen:OnModifyButtonClick()
			end
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(1)
		"
	}
	button
	{
		area 				309 348 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(1,3)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			if multiplayerFromInGame == false then
				local slot = getMultiplayerPlayerControlledCharacterSlot(1,3)
				multiplayerStartSwapPortraits(1,slot)
			elseif multiplayerLocalPlayerID == 1 or multiplayer.player[multiplayerLocalPlayerID].permissions[1] == true then
				multiplayerScreen:OnModifyButtonClick()
			end
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(1)
		"
	}
	button
	{
		area 				340 348 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(1,4)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			if multiplayerFromInGame == false then
				local slot = getMultiplayerPlayerControlledCharacterSlot(1,4)
				multiplayerStartSwapPortraits(1,slot)
			elseif multiplayerLocalPlayerID == 1 or multiplayer.player[multiplayerLocalPlayerID].permissions[1] == true then
				multiplayerScreen:OnModifyButtonClick()
			end
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(1)
		"
	}
	button
	{
		area 				371 348 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(1,5)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			if multiplayerFromInGame == false then
				local slot = getMultiplayerPlayerControlledCharacterSlot(1,5)
				multiplayerStartSwapPortraits(1,slot)
			elseif multiplayerLocalPlayerID == 1 or multiplayer.player[multiplayerLocalPlayerID].permissions[1] == true then
				multiplayerScreen:OnModifyButtonClick()
			end
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(1)
		"
	}
	button
	{
		area 				402 348 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(1,6)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			if multiplayerFromInGame == false then
				local slot = getMultiplayerPlayerControlledCharacterSlot(1,6)
				multiplayerStartSwapPortraits(1,slot)
			elseif multiplayerLocalPlayerID == 1 or multiplayer.player[multiplayerLocalPlayerID].permissions[1] == true then
				multiplayerScreen:OnModifyButtonClick()
			end
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(1)
		"
	}
	--player 2
	button
	{
		area 247 399 180 38
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	button
	{
		area 				247 399 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(2,1)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(2,1)
			multiplayerStartSwapPortraits(2,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	button
	{
		area 				278 399 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(2,2)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(2,2)
			multiplayerStartSwapPortraits(2,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	button
	{
		area 				309 399 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(2,3)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(2,3)
			multiplayerStartSwapPortraits(2,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	button
	{
		area 				340 399 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(2,4)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(2,4)
			multiplayerStartSwapPortraits(2,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	button
	{
		area 				371 399 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(2,5)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(2,5)
			multiplayerStartSwapPortraits(2,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	button
	{
		area 				402 399 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(2,6)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(2,6)
			multiplayerStartSwapPortraits(2,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(2)
		"
	}
	--player 3
	button
	{
		area 247 449 180 38
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	button
	{
		area 				247 449 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(3,1)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(3,1)
			multiplayerStartSwapPortraits(3,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	button
	{
		area 				278 449 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(3,2)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(3,2)
			multiplayerStartSwapPortraits(3,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	button
	{
		area 				309 449 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(3,3)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(3,3)
			multiplayerStartSwapPortraits(3,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	button
	{
		area 				340 449 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(3,4)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(3,4)
			multiplayerStartSwapPortraits(3,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	button
	{
		area 				371 449 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(3,5)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(3,5)
			multiplayerStartSwapPortraits(3,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	button
	{
		area 				402 449 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(3,6)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(3,6)
			multiplayerStartSwapPortraits(3,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(3)
		"
	}
	--player 4
	button
	{
		area 247 500 180 38
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	button
	{
		area 				247 500 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(4,1)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(4,1)
			multiplayerStartSwapPortraits(4,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	button
	{
		area 				278 500 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(4,2)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(4,2)
			multiplayerStartSwapPortraits(4,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	button
	{
		area 				309 500 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(4,3)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(4,3)
			multiplayerStartSwapPortraits(4,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	button
	{
		area 				340 500 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(4,4)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(4,4)
			multiplayerStartSwapPortraits(4,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	button
	{
		area 				371 500 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(4,5)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(4,5)
			multiplayerStartSwapPortraits(4,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	button
	{
		area 				402 500 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(4,6)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(4,6)
			multiplayerStartSwapPortraits(4,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(4)
		"
	}
	--player 5
	button
	{
		area 247 551 180 38
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	button
	{
		area 				247 551 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(5,1)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(5,1)
			multiplayerStartSwapPortraits(5,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	button
	{
		area 				278 551 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(5,2)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(5,2)
			multiplayerStartSwapPortraits(5,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	button
	{
		area 				309 551 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(5,3)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(5,3)
			multiplayerStartSwapPortraits(5,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	button
	{
		area 				340 551 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(5,4)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(5,4)
			multiplayerStartSwapPortraits(5,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	button
	{
		area 				371 551 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(5,5)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(5,5)
			multiplayerStartSwapPortraits(5,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	button
	{
		area 				402 551 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(5,6)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(5,6)
			multiplayerStartSwapPortraits(5,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(5)
		"
	}
	--player 6
	button
	{
		area 247 602 180 38
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}
	button
	{
		area 				247 602 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(6,1)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(6,1)
			multiplayerStartSwapPortraits(6,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}
	button
	{
		area 				278 602 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(6,2)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(6,2)
			multiplayerStartSwapPortraits(6,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}
	button
	{
		area 				309 602 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(6,3)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(6,3)
			multiplayerStartSwapPortraits(6,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}
	button
	{
		area 				340 602 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(6,4)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(6,4)
			multiplayerStartSwapPortraits(6,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}
	button
	{
		area 				371 602 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(6,5)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(6,5)
			multiplayerStartSwapPortraits(6,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}
	button
	{
		area 				402 602 25 38
		bitmap lua			'getMultiplayerPlayerControlledCharacter(6,6)'
		sequence 			1
		align 				center center
		actionSimpleDrag	
		"
			local slot = getMultiplayerPlayerControlledCharacterSlot(6,6)
			multiplayerStartSwapPortraits(6,slot)
		"
		actionSimpleDrop	
		"
			multiplayerStopSwapPortraits(6)
		"
	}

	label -- game name
	{
		area 		40 84 454 56
		text lua	"multiplayerSessionName"
		text style 	'label'
	}
	label -- new game type/save name
	{
		area 		206 140 288 44
		text lua	"multiplayerSaveName"
		text style 	'label'
		align 		left center
	}
	label -- chapter
	{
		area 		206 180 288 44
		text lua	"multiplayerChapter"
		text style 	'label'
		align 		left center
	}
	label -- time played
	{
		area 		206 220 288 44
		text lua	"multiplayerTimePlayed"
		text style 	'label'
		align 		left center
	}
	label -- difficulty
	{
		area 		206 260 288 44
		text lua	"multiplayerDifficultyLabel"
		text style 	'label'
		align 		left center
	}
	label -- other difficulty
	{
		area 		40 140 166 164
		bam			"GUIDIFF"
		frame lua 	"multiplayerDifficultyImage"
		sequence 	0
		align 		center center
	}

	button
	{
		area 524 714 236 44
		bam 'GUIOSTUR'
		sequence 1
		text "START_GAME_BUTTON" -- Done
		text style 'button'
		clickable lua "multiplayer.donebuttonclickable"
		enabled "not multiplayerFromInGame"
		tooltip lua "getStartGameButtonTooltip()"
		action 
		"
			multiplayerScreen:OnMainDoneButtonClick(mulitplayerPreexistingDifficulty)
		"
	}
	button
	{
		on escape
		area 524 714 236 44
		bam 'GUIOSTUR'
		sequence 1
		text "DONE_BUTTON" -- Done
		text style 'button'
		clickable lua "multiplayer.donebuttonclickable"
		enabled "multiplayerFromInGame"
		tooltip lua "getStartGameButtonTooltip()"
		action 
		"
			multiplayerScreen:OnMainDoneButtonClick(mulitplayerPreexistingDifficulty)
		"
	}
	button
	{
		area 284 714 240 44
		bam 'GUIOSTUL'
		sequence 0
		text "LOGOUT_BUTTON" -- Logout
		text style 'button'
		action 
		"
			multiplayerScreen:OnLogoutButtonClick()
		"
	}
	button
	{
		area 294 654 206 44
		bam 'GUIOSTUM'
		sequence 0
		text "MULTIPLAYER_GAME_OPTIONS_BUTTON"
		text style 'button'
		enabled "multiplayerLocalPlayerID == 1"
		action 
		"
			helpTextString = Infinity_FetchString(11323)
			Infinity_PushMenu('MP_OPTIONS')
		"
	}

	--dragged portrait
	label
	{
		name 				"multiplayerDraggingPortraitImage"
		area 				-20 -20 37 57
		bitmap lua			'mpDraggedPortrait'
		sequence 			1
		align 				center center
		enabled 			"multiplayerUpdateDraggedPortrait()"
	}
}
`
multiplayerPermissions = 
{
	{'MULTIPLAYER_PERMISSIONS_MODIFY',	'MULTIPLAYER_PERMISSIONS_MODIFY_TOOLTIP',	false, false, 7},
	{'MULTIPLAYER_PERMISSIONS_GOLD',	'MULTIPLAYER_PERMISSIONS_GOLD_TOOLTIP',		false, false, 0},
	{'MULTIPLAYER_PERMISSIONS_TRAVEL',	'MULTIPLAYER_PERMISSIONS_TRAVEL_TOOLTIP',	false, false, 1},
	{'MULTIPLAYER_PERMISSIONS_VIEW',	'MULTIPLAYER_PERMISSIONS_VIEW_TOOLTIP',		false, false, 3},
	{'MULTIPLAYER_PERMISSIONS_DIALOGUE','MULTIPLAYER_PERMISSIONS_DIALOGUE_TOOLTIP',	false, false, 2},
	{'MULTIPLAYER_PERMISSIONS_PAUSE',	'MULTIPLAYER_PERMISSIONS_PAUSE_TOOLTIP',	false, false, 4}
}

function broadcastPermissionChange(player,permission,setting)
	local player = getMultiplayerPlayerName(player,false,true)
	local todo = t(multiplayerPermissions[permission][1])
	setStringTokenLua("<PLAYER_NAME_1>",player)
	setStringTokenLua("<PERMISSION>",todo)
	if setting == true then
		message = t("MULTIPLAYER_IS_NOW_PERMITTED")
	else
		message = t("MULTIPLAYER_IS_NOT_PERMITTED")
	end
	removeStringTokenLua("<PLAYER_NAME_1>")
	removeStringTokenLua("<PERMISSION>")
	Infinity_SendChatMessage(message, true) 
end

function getMultiplayerPlayerPermissionDescription()
	local player = getMultiplayerPlayerName(multiplayerInPermissionForPlayer,false,false)
	setStringTokenLua("<PLAYER_NAME_1>",player)
 	local canPerform = t("MULTIPLAYER_CAN_PERFORM")
	removeStringTokenLua("<PLAYER_NAME_1>")

	return canPerform
end
`
menu
{
	name 'MP_PERMISSIONS'
	align center center
	modal
	onOpen
	"
		local index = 1
		for index = 0, #(multiplayer.player[multiplayerInPermissionForPlayer].permissions), 1 do
			local luaIndex = -1
			local loopLuaIndex = -1

			for loopLuaIndex = 1, #multiplayerPermissions, 1 do
				if multiplayerPermissions[loopLuaIndex][5] == index then
					luaIndex = loopLuaIndex
					break
				end
			end

			if luaIndex ~= -1 then
				if multiplayer.player[multiplayerInPermissionForPlayer].permissions[index] == true then
					multiplayerPermissions[luaIndex][3] = true
					multiplayerPermissions[luaIndex][4] = true
				elseif multiplayer.player[multiplayerInPermissionForPlayer].permissions[index] == false then
					multiplayerPermissions[luaIndex][3] = false
					multiplayerPermissions[luaIndex][4] = false
				else
					multiplayerPermissions[luaIndex][3] = false
					multiplayerPermissions[luaIndex][4] = false
				end
			end
		end
	"

	label 
	{
		area 0 4 512 656
		mosaic "GUICONNB"
	}
	label
	{
		area 82 70 340 44
		text "PERMISSIONS_TITLE"
		text style "title"
	}

	label
	{
		area 86 114 330 48
		text lua "getMultiplayerPlayerPermissionDescription()"
		text style "title"
	}

	button
	{
		bam GUIOSW
		on esc
		area 462 10 44 44
		sequence 2
		action 
		"	
			multiplayerScreen:OnCancelButtonClick()
			Infinity_PopMenu()
		"
	}

	--bottom buttons
	button
	{
		area 152 534 200 44
		bam 'GUIOSTUM'
		sequence 0
		text "CANCEL_BUTTON" -- Back
		text style 'button'
		action 
		"
			multiplayerScreen:OnCancelButtonClick()
			Infinity_PopMenu()
		"
	}
	button
	{
		on return
		area 152 586 200 44
		bam 'GUIOSTUM'
		sequence 1
		text "DONE_BUTTON" -- Done
		text style 'button'
		enabled "multiplayerLocalPlayerID == 1"
		action 
		"
			local index = 1
			for index = #(multiplayerPermissions), 1, -1 do
				if multiplayerPermissions[index][3] ~= multiplayerPermissions[index][4] then
					broadcastPermissionChange(multiplayerInPermissionForPlayer,index,multiplayerPermissions[index][3])
					multiplayerScreen:OnPermissionButtonClick(multiplayerInPermissionForPlayer - 1, multiplayerPermissions[index][5])
				end
			end

			multiplayerInPermission = false
			multiplayerScreen:OnDoneButtonClick()
			Infinity_PopMenu()
		"
	}

	--permissions
	button
	{
		area 165 176 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerPermissions[1][3] == true"
		tooltip lua "t(multiplayerPermissions[1][2])"
		align center center
		action 
		"
			if multiplayerLocalPlayerID == 1 then
				multiplayerPermissions[1][3] = not multiplayerPermissions[1][3]
			end
		"
	}
	text
	{
		area 210 170 212 56
		text lua "t(multiplayerPermissions[1][1])"
		tooltip lua "t(multiplayerPermissions[1][2])"
		text style "normal"
		align left center
	}
	button
	{
		area 165 232 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerPermissions[2][3] == true"
		tooltip lua "t(multiplayerPermissions[2][2])"
		align center center
		action 
		"
			if multiplayerLocalPlayerID == 1 then
				multiplayerPermissions[2][3] = not multiplayerPermissions[2][3]
			end
		"
	}
	text
	{
		area 210 226 212 56
		text lua "t(multiplayerPermissions[2][1])"
		tooltip lua "t(multiplayerPermissions[2][2])"
		text style "normal"
		align left center
	}
	button
	{
		area 165 286 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerPermissions[3][3] == true"
		tooltip lua "t(multiplayerPermissions[3][2])"
		align center center
		action 
		"
			if multiplayerLocalPlayerID == 1 then
				multiplayerPermissions[3][3] = not multiplayerPermissions[3][3]
			end
		"
	}
	text
	{
		area 210 282 212 56
		text lua "t(multiplayerPermissions[3][1])"
		tooltip lua "t(multiplayerPermissions[3][2])"
		text style "normal"
		align left center
	}
	button
	{
		area 165 338 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerPermissions[4][3] == true"
		tooltip lua "t(multiplayerPermissions[4][2])"
		align center center
		action 
		"
			if multiplayerLocalPlayerID == 1 then
				multiplayerPermissions[4][3] = not multiplayerPermissions[4][3]
			end
		"
	}
	text
	{
		area 210 334 212 56
		text lua "t(multiplayerPermissions[4][1])"
		tooltip lua "t(multiplayerPermissions[4][2])"
		text style "normal"
		align left center
	}
	button
	{
		area 165 394 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerPermissions[5][3] == true"
		tooltip lua "t(multiplayerPermissions[5][2])"
		align center center
		action 
		"
			if multiplayerLocalPlayerID == 1 then
				multiplayerPermissions[5][3] = not multiplayerPermissions[5][3]
			end
		"
	}
	text
	{
		area 210 390 212 56
		text lua "t(multiplayerPermissions[5][1])"
		tooltip lua "t(multiplayerPermissions[5][2])"
		text style "normal"
		align left center
	}
	button
	{
		area 165 450 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerPermissions[6][3] == true"
		tooltip lua "t(multiplayerPermissions[6][2])"
		align center center
		action 
		"
			if multiplayerLocalPlayerID == 1 then
				multiplayerPermissions[6][3] = not multiplayerPermissions[6][3]
			end
		"
	}
	text
	{
		area 210 446 212 56
		text lua "t(multiplayerPermissions[6][1])"
		tooltip lua "t(multiplayerPermissions[6][2])"
		text style "normal"
		align left center
	}
}
`
multiplayerGameOptions =
{
	{"LISTEN_JOIN_LABEL",	"LISTEN_JOIN_TOOLTIP",	false, false},
	{"ALLOW_REFORM_LABEL",	"ALLOW_REFORM_TOOLTIP",	false, false}
}
multiplayerImportOptions =
{
	{"MULTIPLAYER_IMPORT_CHARACTER_RULES_SEI"},
	{"MULTIPLAYER_IMPORT_CHARACTER_RULES_SE"},
	{"MULTIPLAYER_IMPORT_CHARACTER_RULES_S"}
}
multiplayerImportOption = 0

function broadcastOptionChange(slot, onOff)
	if multiplayerLocalPlayerID == 1 then
		local message = ""
		if slot < 3 then
			local setting = t(multiplayerGameOptions[slot][1])
			setStringTokenLua("<SESSION_RULES>",setting)
			if onOff == true then
				message = t("MULTIPLAYER_GAME_WILL_NOW")
			else
				message = t("MULTIPLAYER_GAME_WILL_NO_LONGER")
			end
			removeStringTokenLua("<SESSION_RULES>")
		else
			local setting = t(multiplayerImportOptions[slot-2][1])
			setStringTokenLua("<IMPORT_RULES>",setting)
			message = t("MULTIPLAYER_IMPORT_SETTINGS_CHANGE")
			removeStringTokenLua("<IMPORT_RULES>")
		end
		Infinity_SendChatMessage(message, true) 
	end
end
`
menu
{
	name 'MP_OPTIONS'
	align center center
	modal 
	onOpen
	"
		multiplayerGameOptions[1][3] = multiplayer.listentojoin
		multiplayerGameOptions[1][4] = multiplayerGameOptions[1][3]
		multiplayerGameOptions[2][3] = multiplayer.allowreformparty
		multiplayerGameOptions[2][4] = multiplayerGameOptions[2][3]
		multiplayerImportOption = multiplayer.importsetting + 1
	"

	label 
	{
		area 0 4 488 656
		mosaic "GUICONNB"
	}
	label
	{
		area 82 70 340 44
		text "OPTIONS_TITLE"
		text style "title"
	}
	label
	{
		area 74 262 348 56
		text "MULTIPLAYER_IMPORT_CHARACTER_RULES_LABEL"
		text style "title"
		align center center
	}

	button
	{
		area 107 136 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerGameOptions[1][3] == true"
		tooltip lua "t(multiplayerGameOptions[1][2])"
		align center center
		action 
		"
			multiplayerGameOptions[1][3] = not multiplayerGameOptions[1][3]
		"
	}
	text
	{
		area 152 130 212 55
		text lua "t(multiplayerGameOptions[1][1])"
		text style "normal"
		tooltip lua "t(multiplayerGameOptions[1][2])"
		align left center
	}
	button
	{
		area 107 200 45 42
		bam ROUNDBUT
		sequence 0
		glow lua "multiplayerGameOptions[2][3] == true"
		tooltip lua "t(multiplayerGameOptions[2][2])"
		align center center
		action 
		"
			multiplayerGameOptions[2][3] = not multiplayerGameOptions[2][3]
		"
	}
	text
	{
		area 152 194 212 55
		text lua "t(multiplayerGameOptions[2][1])"
		text style "normal"
		tooltip lua "t(multiplayerGameOptions[2][2])"
		align left center
	}

	button
	{
		area 107 342 45 42
		bam ROUNDBUT
		frame lua "currentCellCheck(3)"
		sequence 0
		glow lua "multiplayerImportOption == 1"
		tooltip lua "t('IMPORT_RULES_TOOLTIP')"
		align center center
		action 
		"
			multiplayerImportOption = 1
		"
	}
	text
	{
		area 152 336 212 55
		text lua "t('MULTIPLAYER_IMPORT_CHARACTER_RULES_SEI')"
		tooltip lua "t('IMPORT_RULES_TOOLTIP')"
		text style "normal"
		align left center
	}
	button
	{
		area 107 400 45 42
		bam ROUNDBUT
		frame lua "currentCellCheck(3)"
		sequence 0
		glow lua "multiplayerImportOption == 2"
		tooltip lua "t('IMPORT_RULES_TOOLTIP')"
		align center center
		action 
		"
			multiplayerImportOption = 2
		"
	}
	text
	{
		area 152 391 212 55
		text lua "t('MULTIPLAYER_IMPORT_CHARACTER_RULES_SE')"
		tooltip lua "t('IMPORT_RULES_TOOLTIP')"
		text style "normal"
		align left center
	}
	button
	{
		area 107 452 45 42
		bam ROUNDBUT
		frame lua "currentCellCheck(3)"
		sequence 0
		glow lua "multiplayerImportOption == 3"
		tooltip lua "t('IMPORT_RULES_TOOLTIP')"
		align center center
		action 
		"
			multiplayerImportOption = 3
		"
	}
	text
	{
		area 152 446 212 56
		text lua "t('MULTIPLAYER_IMPORT_CHARACTER_RULES_S')"
		tooltip lua "t('IMPORT_RULES_TOOLTIP')"
		text style "normal"
		align left center
	}

	button
	{
		bam GUIOSW
		on esc
		area 444 8 44 44
		sequence 2
		action 
		"	
			multiplayerScreen:OnCancelButtonClick()
			Infinity_PopMenu()
		"
	}

	--bottom buttons
	button
	{
		on return
		area 152 590 200 44
		bam 'GUIOSTUM'
		sequence 0
		text "DONE_BUTTON" -- Done
		text style 'button'
		action 
		"
			if multiplayerImportOption ~= multiplayer.importsetting + 1 then
				multiplayerScreen:SetImportSetting(multiplayerImportOption - 1)
				broadcastOptionChange(multiplayerImportOption+2)
			end

			if multiplayerGameOptions[1][3] ~= multiplayerGameOptions[1][4] then
				broadcastOptionChange(1, multiplayerGameOptions[1][3])
				multiplayerScreen:ToggleListenToJoin()
			end

			if multiplayerGameOptions[2][3] ~= multiplayerGameOptions[2][4] then
				broadcastOptionChange(2, multiplayerGameOptions[2][3])
				multiplayerScreen:ToggleAllowReformParty()
			end

			Infinity_PopMenu()
		"
	}
	button
	{
		on escape
		area 152 536 200 44
		bam 'GUIOSTUM'
		sequence 1
		text "CANCEL_BUTTON" -- Cancel
		text style 'button'
		action 
		"
			multiplayerScreen:OnCancelButtonClick()
			Infinity_PopMenu()
		"
	}
}
`
	function getActivePlayerIndex(index)
		local ret = -1
		local count = 0
		local slot = 0

		for slot = 1, 6, 1 do
			if mpaPlayers[slot]["name"] ~= '' then
				count = count + 1
			end
			if count == index then
				ret = slot
				break
			end
		end

		return ret
	end
`
menu
{
	name 'MP_PICKPLAYER'
	align center center
	modal 
	label 
	{
		mosaic 'GUICONN1'
		area 0 0 512 551
	}
	label 
	{
		area 56 60 390 44
		text "SELECT_PLAYER_TITLE"
		text style "title"
	}

	-- list
	list
	{
		column
		{
			width 100
			label
			{
				area 0 0 340 32
				text lua "getMultiplayerPlayerName(getActivePlayerIndex(rowNumber), false, true)"
				text style "normal"
				align left center
			}
		}

		action 
		"
		"

		rowheight 32
		area 124 116 258 194
		table "multiplayer.player"
		var currentMultiplayerSelectPlayer
	}
	
	button
	{
		bam GUIOSW
		on esc
		area 464 4 44 44
		sequence 2
		action 
		"	
			Infinity_PopMenu()
		"
	}

	button
	{
		on escape
		area 152 408 204 44
		text "CANCEL_BUTTON"
		text style "button"
		align center center
		bam 'GUIOSTUM'
		sequence 0
		action
		"	
			Infinity_PopMenu()
		"
	}
	button
	{
		on escape
		area 152 458 204 44
		text "DONE_BUTTON"
		text style "button"
		align center center
		bam 'GUIOSTUM'
		sequence 0
		action
		"	
			if mpaCharacters[selectedCharacter]['ready'] == true and mpaCharacters[selectedCharacter]['player'] ~= getActivePlayerIndex(currentMultiplayerSelectPlayer) then
				multiplayerScreen:OnReadyButtonClick(selectedCharacter-1)
			end
			broadcastCharacterControlChange(selectedCharacter, getActivePlayerIndex(currentMultiplayerSelectPlayer))
			multiplayerScreen:OnPlayerSelection(getActivePlayerIndex(currentMultiplayerSelectPlayer)-1)
			Infinity_PopMenu()
		"
	}
}
`
	function multiplayerIsDelete ()
		if (multiplayer.character[mpModifyingCharacter+1].portrait ~= '') then
			return t("DELETE_BUTTON")
		else
			return t("CREATE_BUTTON")
		end
	end
	function getModifyConfirmationLabel()
		return t('MULTIPLAYER_EDIT_CONFIRM').. ' ' .. getMultiplayerCharacterName(mpModifyingCharacter+1)
	end
`
menu
{
	name 'MP_MODIFYCHARACTER'
	align center center
	modal 
	label 
	{
		mosaic 'GUIERR6'
		area 0 0 682 234
	}
	label
	{
		area 14 8 628 124
		text lua "getModifyConfirmationLabel()"
		text style "title"
		align center center
	}
	button
	{
		on escape
		area 79 170 234 44
		text "CANCEL_BUTTON" -- cancel
		text style "button"
		align center center
		bam GUIOSTUL
		action
		"	
			Infinity_PopMenu()
		"
	}
	button
	{
		on return
		area 343 170 234 44
		text lua "multiplayerIsDelete()"
		text style "button"
		align center center
		bam GUIOSTUR
		action
		"	
			Infinity_PopMenu()
			multiplayerScreen:SetModifiedCharacterSlot(mpModifyingCharacter)
			if (multiplayer.character[mpModifyingCharacter+1].portrait ~= '') then
				multiplayerScreen:OnModifyCharacterDelete()
			else
				multiplayerScreen:UpdateModifyCharacterPanel()
			end
		"
	}
}

menu
{
	name 'MP_ERRORONE'
	align center center
	modal 
	label 
	{
		mosaic 'GUIERR6'
		area 0 0 657 253
	}
	label
	{
		area 29 21 600 126
		text lua "Infinity_FetchString( mpErrorText )"
		text style "normal"
		align center center
	}
	button
	{
		on return
		area 213 170 230 44
		text "DONE_BUTTON" -- done
		text style "button"
		align center center
		bam GUIBUTMT
		action
		"	
			Infinity_PopMenu()
		"
	}
}

menu
{
	name 'MP_ERRORTWO'
	align center center
	modal 
	label 
	{
		mosaic 'GUIERR'
		area 0 0 408 418
	}
	label
	{
		area 72 82 258 80
		text lua "Infinity_FetchString( mpErrorText )"
		text style "normal"
		align center center
	}
	button
	{
		on return
		enabled "mpErrorState == 2"
		area 52 220 302 44
		text "MODIFY_BUTTON" -- modify
		text style "button"
		align center center
		bam GUIOSTCL
		action
		"	
			Infinity_PopMenu()
			multiplayerScreen:ModifyCharacters()
		"
	}
	button
	{
		on return
		enabled "mpErrorState == 3"
		area 52 220 302 44
		text "KICK_BUTTON" -- kick player
		text style "button"
		align center center
		bam GUIOSTCL
		action
		"	
			Infinity_PopMenu()
			multiplayerScreen:KickPlayer()
		"
	}
	button
	{
		on return
		enabled "mpErrorState == 4"
		area 52 220 302 44
		text "LOGOUT_BUTTON" -- log out
		text style "button"
		align center center
		bam GUIOSTCL
		action
		"	
			local index = 1
			Infinity_PopMenu()
			multiplayerScreen:Logout()
		"
	}
	button
	{
		on escape
		area 102 318 204 44
		text "CANCEL_BUTTON" -- cancel
		text style "button"
		align center center
		bam GUIOSTUM
		action
		"	
			Infinity_PopMenu()
		"
	}
}
`
	function dragMPChat(newY)
		--do a quick bounds check.
		local area = {Infinity_GetArea("mpChatDisplayBackground")}
		if(area[4] + newY <= 150) then newY = 150 - area[4] end
		
		area = {Infinity_GetArea("mpChatHandle")}
		local screenWidth, screenHeight = Infinity_GetScreenSize()
		if(area[2] + area[4] + newY > screenHeight) then newY = screenHeight - area[2] - area[4] end
		
		adjustItemGroup({"mpChatDisplayBackground","mpChatDisplay"}, 0, 0, 0, newY)
		adjustItemGroup({"mpChatEditBackground","mpChatEdit","mpChatHandle"}, 0, newY, 0 , 0)
	end
	mpChatTable = {}
	showMpChat = 0
	function updateChatViewed()
		if(showMpChat == 0) then chatViewed = 0 end
	end
	function updateMPChatPreview(message)
		if(showMpChat == 0) then table.insert(mpChatTable,{text = message}) end
	end
	function getMPMessageOpacity()
		local current = mpChatTable[#mpChatTable]
		if(current == nil) then
			return 0
		end
		if(current.displayTime == nil) then
			current.displayTime = 500
			
			--set the box size
			Infinity_ScaleToText("mpChatPreview")
			
			--give some extra room for the padding
			adjustItemGroup({"mpChatPreview"},0,0,0,16)
		end
		if(current.displayTime > 0) then
			current.displayTime = current.displayTime - 4
		end
		if(current.displayTime > 255) then
			return 255
		else
			return current.displayTime
		end
	end
	function getMPMessage()
		if(#mpChatTable > 0 and mpChatTable[#mpChatTable].displayTime ~= nil) then 
			return mpChatTable[#mpChatTable].text 
		end
		return nil
	end
	function getChatIconOpacity()
		if(chatViewed == 1) then return 255 end
		local sinWave = math.sin(Infinity_GetFrameCounter() / 15)
		local sinWaveAdjusted = (sinWave / 2) + 0.5
		return sinWaveAdjusted * 255
	end
	function getChatBarTooltip()
		if(showMpChat == 0) then
			return t("MULTIPLAYER_CHAT_BAR_COLLAPSED")
		else
			return t("MULTIPLAYER_CHAT_BAR_EXPANDED")
		end
	end
	function resizeMpEditBox()
		Infinity_ScaleToText('mpChatEdit')
		local x,y,w,h = Infinity_GetArea('mpChatEdit')
		local offset = 20
		if(h + offset < 42) then h = (42 - offset) end
		
		
		Infinity_SetArea('mpChatEdit',x,y,w,h)
		Infinity_SetArea('mpChatEditBackground',nil,nil,nil,h + offset)
		Infinity_SetArea('mpChatHandle',nil,y+h+(offset/2),nil,nil)
	end

	function mpChatboxScroll(top, height, contentHeight)
		if(mpChatboxJumpToBottom and contentHeight > height) then
			mpChatboxJumpToBottom = nil
			return height-contentHeight
		end
		if(mpChatboxScrollToBottom == 0 and mpChatboxScrollLastHeight == contentHeight) then
			--defer to default scrolling
			return nil
		elseif mpChatboxScrollToBottom == 0 then
			mpChatboxScrollLastHeight = contentHeight
			return height-contentHeight
		end
		if(contentHeight < height) then
			--no scrolling required, content fits
			mpChatboxScrollToBottom = nil
			return nil
		end
		local dT = Infinity_GetClockTicks() - mpChatboxScrollTimeLast
		mpChatboxScrollTimeLast = Infinity_GetClockTicks()
		top = top + lastTrimmedContentHeight
		lastTrimmedContentHeight = 0
		local newTop = (dT * -0.25) + top
		if (newTop + contentHeight > height + 200) then
			return (height - contentHeight + 200)
		end
		if(newTop + contentHeight < height) then
			mpChatboxScrollToBottom = 0
			return height - contentHeight
		end
		return newTop
	end

	mpChatboxScrollLastHeight = 0
	mpChatboxScrollToBottom = nil
	mpChatboxScrollTimeLast = 0
	mpChatEditOverlay = ""
`
menu
{
	name "MP_CHAT_OVERLAY"
	enabled "e:IsMultiplayer()"
	align right top
	ignoreEsc
	offset -80 0
	onOpen
	"
		chatViewed = 1
	"
	label
	{
		name "mpChatDisplayBackground"
		enabled "showMpChat"
		area 0 0 300 372
		rectangle 4
		rectangle opacity 200
	}
	label
	{
		area 0 0 300 42
		rectangle 0

	}
	label
	{
		area 10 8 28 28
		bam "CHTICN"
		frame 1
		opacity lua "getChatIconOpacity()"
		
	}
	label
	{
		area 10 8 28 28
		bam "CHTICN"
		frame 0
		opacity lua "255 - getChatIconOpacity()"
	}
	label
	{
		area 42 0 252 42
		text "MULTIPLAYER_CHAT_LABEL"
		text style "label"
	}
	button
	{
		area 0 0 300 42
		toggle "showMpChat"
		tooltip lua "getChatBarTooltip()"
		action
		"
			chatViewed = 1
			mpChatboxScrollToBottom = 1
			if showMpChat == 1 then
				Infinity_FocusTextEdit('mpChatEdit')
			else
				Infinity_FocusTextEdit('')
			end
		"
	}
	
	label
	{
		name "mpChatPreview"
		enabled "showMpChat == 0"
		opacity lua "getMPMessageOpacity()"
		area 0 42 300 18
		text style "normal"
		text lua "getMPMessage()"
		ignoreEvents
		pad 8 8 8 8
		rectangle 1
	}
	text
	{
		name "mpChatDisplay"
		enabled "showMpChat"
		area 22 54 256 268
		text lua "mpChatText"
		scrollbar 'GUISCRC'
		scrollbar func "mpChatboxScroll"
		text style	normal
	}
	label
	{
		name "mpChatEditBackground"
		enabled "showMpChat"
		area 0 324 300 42
		rectangle 0
	}
	edit
	{
		name		"mpChatEdit"
		enabled 	"showMpChat"
		area		10 334 290 24
		var			mpChatEditOverlay
		scrollbar	'GUISCRC'
		text style	"edit"
		maxchars 255
		action
		"
			--On return pressed
			if (key_pressed == 13) then
				if (mpChatEditOverlay ~= '') then
					Infinity_SendChatMessage(mpChatEditOverlay, false) 
					Infinity_PlaySound('WAL_19B')
					mpChatEditOverlay=''
					resizeMpEditBox()
					mpChatboxScrollToBottom = 1
					return -1
				end
			end
			return 1
		"
		actionalt
		"
			resizeMpEditBox()
		"
	}
	handle
	{
		name "mpChatHandle"
		area 104 366 95 38
		bam "MPCHATAB"
		enabled "showMpChat"
		tooltip lua "t('MULTIPLAYER_CHAT_RESIZE_TOOLTIP')"
		actionDrag
		"
			dragMPChat(motionY)
		"
	}
}
`
function reinitQuests()
	for questIdx, quest in pairs(quests) do
		local noquest = true
		for objIdx,objective in pairs(quest.objectives) do
			local noobjective = true
			for entryIdx,entry in pairs(objective.entries) do
				if quests[questIdx].objectives[objIdx].entries[entryIdx].stateType ~= const.ENTRY_TYPE_NONE and quests[questIdx].objectives[objIdx].entries[entryIdx].stateType ~= nil then
					noobjective = false
				end
			end
			if noobjective then
				quests[questIdx].objectives[objIdx].stateType = const.ENTRY_TYPE_NONE
			end
			if quests[questIdx].objectives[objIdx].stateType ~= const.ENTRY_TYPE_NONE and quests[questIdx].objectives[objIdx].stateType ~= nil then
				noquest = false
			end
		end
		if noquest then
			quests[questIdx].stateType = const.ENTRY_TYPE_NONE
		end
	end
end

function initQuests()
	--instead of always searching the quests, just map entry ids to their quests
	entryToQuest = {}
	buildQuestsTable()
	for questIdx, quest in pairs(quests) do
		quests[questIdx].stateType = const.ENTRY_TYPE_NONE
		for objIdx,objective in pairs(quest.objectives) do
			quests[questIdx].objectives[objIdx].stateType = const.ENTRY_TYPE_NONE
			for entryIdx,entry in pairs(objective.entries) do
				quests[questIdx].objectives[objIdx].entries[entryIdx].stateType = const.ENTRY_TYPE_NONE
				entryToQuest[entry.id] = questIdx
			end
		end
	end
end

function compareByRecvTime(o1,o2)
	if(not o1.recvTime and not o2.recvTime) then return false end
	if(not o1.recvTime) then return false end
	if(not o2.recvTime) then return true end
	return o1.recvTime > o2.recvTime
end

function buildEntry(text, recvTime, stateType, chapter, timeStamp)
	local entry = 
		{
			text = text,
			recvTime = recvTime,
			stateType = stateType,
			timeStamp = timeStamp,
			chapters = {}
		}
	entry.chapters[chapter] = 1
	return entry	
end

--Update a journal entry by the strref/journalId
function updateJournalEntry(journalId, recvTime, stateType, chapter, timeStamp)
	if(stateType == const.ENTRY_TYPE_USER) then
		local entry = buildEntry(journalId, recvTime, stateType, chapter, timeStamp)
		table.insert(userNotes,entry)
		
		--update display data
		buildQuestDisplay()
		return
	end
	--find the quest that is parent to this entry.
	--NOTE this can be placed in a loop if there needs to be more than quest to an entry
	--this would just mean entryToQuest returns a table that we iterate over
	local questId = entryToQuest[journalId]
	if questId == nil or stateType == const.ENTRY_TYPE_INFO then
		--add loose entries into the looseEntries table so they still get displayed.
		for _,entry in pairs(looseEntries) do
			if entry.text == journalId then
				return
			end
		end
		local entry = buildEntry(journalId, recvTime, stateType, chapter, timeStamp)
		table.insert(looseEntries,entry)
		
		--update display data
		buildQuestDisplay()
		return
	end

	local quest = quests[questId]
	if quest == nil then
		print("JOURNAL ERROR - no quest entry associated with questId "..questId)
		return
	end

	local previous = nil
	--traverse quest to find objective and entry
	for objIdx,objective in pairs(quest.objectives) do
		for entryIdx,entry in pairs(objective.entries) do
			if(entry.id == journalId) then
				--now we know where our quest, objective, and entry are
				--update quest, objective and entry appropriately
				entry.recvTime = recvTime
				entry.stateType = stateType
				if(not entry.chapters) then entry.chapters = {} end
				entry.chapters[chapter] = 1
				entry.timeStamp = timeStamp
				objective.entries[entryIdx] = entry
				
				objective.recvTime = recvTime
				if(not objective.chapters) then objective.chapters = {} end
				objective.chapters[chapter] = 1
				if(objective.stateType ~= const.ENTRY_TYPE_COMPLETE) then
					objective.stateType = stateType
				end
				quest.objectives[objIdx] = objective
				
				quest.recvTime = recvTime
				if(not quest.chapters) then quest.chapters = {} end
				quest.chapters[chapter] = 1
				if(quest.stateType ~= const.ENTRY_TYPE_COMPLETE) then
					quest.stateType = stateType
				end
				
				--mark any previous objective as complete
				if(entry.previous ~= nil) then
					for objIdx2,objective2 in pairs(quest.objectives) do
						for k, prevObj in pairs(entry.previous) do
							if(prevObj == objective2.text) then
								quest.objectives[objIdx2].stateType = const.ENTRY_TYPE_COMPLETE
							end
						end
					end
				end
				
				quests[questId] = quest
				
				--remove all in subgroup (except myself!)
				if(stateType == const.JOURNAL_STATE_COMPLETE and entry.subGroup) then
					for k,v in pairs(subGroups[entry.subGroup]) do
						Infinity_Log("Checking subgroup, id = " .. v.id)
						if(v.id ~= entry.id) then
							removeJournalEntry(v.id)
						end
					end
				end
				
			end
		end
	end
	--sort the objectives.
	table.sort(quest.objectives,compareByRecvTime)
	
	--update display data
	buildQuestDisplay()
end
function checkEntryComplete(journalId, stateType)
	--Check if a journal entry is part of a quest that's already complete
	
	--If anything other than an unfinished entry return false.
	if(stateType ~= const.ENTRY_TYPE_INPROGRESS) then return false end
	
	--Check if my quest is marked complete.
	local questIndex = entryToQuest[journalId]
	if (quests[questIndex].stateType == const.ENTRY_TYPE_COMPLETE) then
		return 1
	else
		return 0
	end
end
--this should maybe be done recursively, but i kinda want direct control over each level
function buildQuestDisplay()
	--this is basically just a flatten
	questDisplay = {}
	journalDisplay = {}
	local journalEntries = {}
	for k,quest in pairs(quests) do
		--skip inactive quests
		if(quest.stateType ~= nil and quest.stateType ~= const.ENTRY_TYPE_NONE) then
			quest.quest = 1 -- tell the renderer what type of entry this is
			table.insert(questDisplay, quest)
			local curQuestIdx = #questDisplay --we'll need to modify current quest with it's children, store a reference.
			local questChildren = {}
			for k2,objective in pairs(quest.objectives) do
				if(objective.stateType ~= const.ENTRY_TYPE_NONE) then
					objective.objective = 1
					objective.parent = curQuestIdx
					
					--fix for missing data in bg1 and bg2.
					--if we have an objective title unique from the quest, use it. otherwise use the timestamp from my first(only) entry.
					if(objective.text == Infinity_FetchString(quest.text) or objective.text == nil) then
						objective.text = objective.entries[1].timeStamp
					end
					
					if(objective.stateType ~= const.ENTRY_TYPE_INFO) then
						--info entries should not go into quests
						table.insert(questDisplay, objective)
						table.insert(questChildren, #questDisplay)
					end
					local curObjectiveIdx = #questDisplay
					local objectiveChildren = {}
					for k3,entry in pairs(objective.entries) do
						entry.entry = 1
						
						entry.parent = curObjectiveIdx
						table.insert(questDisplay, entry)
						table.insert(objectiveChildren, #questDisplay)
					end
					questDisplay[curObjectiveIdx].children = objectiveChildren
				end
			end
			questDisplay[curQuestIdx].children = questChildren
		end
	end
	
	--add the loose entries (entries without quests) to the journal display
	for k,entry in pairs(looseEntries) do
		entry.entry = 1
		table.insert(journalEntries,entry)
	end
	
	-- add the user entries to the journal display
	for k,entry in pairs(userNotes) do
		entry.entry = 1
		table.insert(journalEntries,entry)
	end
	
	--sort the entries
	table.sort(journalEntries, compareByRecvTime)
	
	for k,entry in pairs(journalEntries) do
		local title  = {}
		title.title = 1
		title.text = entry.timeStamp
		title.chapters = entry.chapters
		table.insert(journalDisplay,title)
		table.insert(journalDisplay, entry)
	end
end
function questContainsSearchString(row)
	if(journalSearchString == nil or journalSearchString == "") then return 1 end --no search string, do nothing
	local text = Infinity_FetchString(questDisplay[row].text)
	if(string.find(string.lower(text),string.lower(journalSearchString))) then return 1 end -- string contains search string.
	if(questDisplay[row].children == nil) then return nil end --no children, does not contain search string.
	for k,v in pairs(questDisplay[row].children) do
		--Infinity_Log(v)
		if(containsSearchString(v)) then return 1 end -- one of children contains search string
	end
	return nil --does not contain search string
end
function containsChapter(tab, chapter)
	if(not tab) then return nil end
	return tab[chapter]
end
function entryEnabled(row)
	local rowTab =  questDisplay[row]
	if(rowTab == nil or rowTab.entry == nil or not containsChapter(rowTab.chapters,chapter)) then return nil end

	if(objectiveEnabled(rowTab.parent) and questDisplay[rowTab.parent].expanded) then return 1 else return nil end
end
function getEntryText(row)
	return questDisplay[row].text
end

function objectiveEnabled(row)
	local rowTab =  questDisplay[row]
	if(rowTab == nil or rowTab.objective == nil or not containsChapter(rowTab.chapters,chapter)) then return nil end

	if(questEnabled(rowTab.parent) and questDisplay[rowTab.parent].expanded) then return 1 else return nil end
end
function getObjectiveText(row)
	local rowTab =  questDisplay[row]
	if (rowTab == nil) then return nil end
	local text = rowTab.text
	if(text == "" or text == nil) then
		text = t("NO_OBJECTIVE_NORMAL")
	end
	--objectives shouldn't really display a completed state since they don't actually follow a progression.
	--if(getFinished(row)) then
	--	text = "^0xFF666666" .. text .. " (Finished)^-"
	--end

	return text
end

function questEnabled(row)
	return (questDisplay[row] and questDisplay[row].quest and containsChapter(questDisplay[row].chapters,chapter) and (#questDisplay[row].children > 0))
end
function getQuestText(row)
	local rowTab =  questDisplay[row]
	if (rowTab == nil) then return nil end
	local text = Infinity_FetchString(rowTab.text)
	
	if(getFinished(row)) then
		text = "^0xFFaaaaaa" .. text .. " (" .. t("OBJECTIVE_FINISHED_NORMAL") .. ")^-"
	end

	return text
end
function getArrowFrame(row)
	if(questDisplay[row] == nil or (questDisplay[row].objective == nil and questDisplay[row].quest == nil)) then return "" end

	
	if(questDisplay[row].expanded) then
		return 0
	else
		return 1
	end
end
function getArrowEnabled(row)
	if(questDisplay[row].quest == nil and questDisplay[row].objective == nil) then return nil end
	if(questDisplay[row].objective and not objectiveEnabled(row)) then return nil end
	if(questDisplay[row].quest and not questEnabled(row)) then return nil end
	return 1
end

function getFinished(row)
	if(questDisplay[row].stateType == const.ENTRY_TYPE_COMPLETE) then return 1 else return nil end
end
function showObjectiveSeperator(row)
	local tab = questDisplay[row]
	if(objectiveEnabled(row) or entryEnabled(row)) then
		--seperator is enabled for objective or entry as long as the next thing is an objective.
		--search until we find something enabled or end of table.
		local idx = row + 1
		while(questDisplay[idx]) do
			if(objectiveEnabled(idx)) then
				return 1
			else 
				if(questEnabled(idx) or entryEnabled(idx)) then
					return nil
				end
			end
			idx = idx + 1
		end
	end
end


function getJournalTitleEnabled(row)
	return journalDisplay[row].title and containsChapter(journalDisplay[row].chapters,chapter) and journalContainsSearchString(row)
end
function getJournalTitleText(row)
	return journalDisplay[row].text
end
function getJournalEntryEnabled(row)
	return journalDisplay[row].entry and containsChapter(journalDisplay[row].chapters,chapter) and journalContainsSearchString(row)
end
function getJournalEntryText(row)
	local text = Infinity_FetchString(journalDisplay[row].text)
	if(text == nil or text == "") then
		text = journalDisplay[row].text
	end
	
	if(journalSearchString and journalSearchString ~= "") then
		--do the search string highlight
		text = highlightString(text, journalSearchString, "^0xFF0000FF")
	end
	
	return text
end
function getJournalDarken(row)
	local entry = journalDisplay[row]
	if(entry.title) then
		return (row == selectedJournal or row + 1 == selectedJournal)
	end
	if(entry.entry) then
		return (row == selectedJournal or row - 1 == selectedJournal)
	end
end
function journalContainsSearchString(row)
	if(journalSearchString == nil or journalSearchString == "") then return 1 end --no search string, do nothing
	local text = Infinity_FetchString(journalDisplay[row].text)
	if(text == "") then text = journalDisplay[row].text end --no stringref, use the text.
	if(string.find(string.lower(text),string.lower(journalSearchString))) then return 1 end -- string contains search string.
	
	--check if the corresponding row to this one contains the string.
	local pairText = nil
	if(journalDisplay[row].title) then
		--check the corresponding entry
		pairText = Infinity_FetchString(journalDisplay[row+1].text) or journalDisplay[row+1].text
		if(pairText == "") then pairText = journalDisplay[row+1].text end 
	else 
		if (journalDisplay[row].entry) then
			pairText = Infinity_FetchString(journalDisplay[row-1].text) or journalDisplay[row-1].text
			if(pairText == "") then pairText = journalDisplay[row-1].text end 
		end
	end
	if(string.find(string.lower(pairText),string.lower(journalSearchString))) then return 1 end -- pair string contains search string.
	
	return nil --does not contain search string
end
function dragJournal()
	local offsetX,offsetY,menuWidth,menuHeight = Infinity_GetMenuArea('JOURNAL')
	offsetX = offsetX + motionX
	offsetY = offsetY + motionY
	
	--clamping
	if(offsetX < 80) then
		offsetX = 80
	end
	if(offsetY < 0) then
		offsetY = 0
	end
	
	local screenWidth, screenHeight = Infinity_GetScreenSize()
	if(offsetX > screenWidth - 80 - menuWidth) then
		offsetX = screenWidth - 80 - menuWidth
	end
	if(offsetY > screenHeight - menuHeight) then
		offsetY = screenHeight - menuHeight
	end
	
	Infinity_SetOffset('JOURNAL', offsetX, offsetY)
end
function journalEntryClickable(selectedJournal)
	local entry = journalDisplay[selectedJournal]
	if(entry) then return true end
end
function getJournalEntryRef(selectedJournal)
	local entry = journalDisplay[selectedJournal]
	if(not entry) then return end
	if(entry.title) then
		return journalDisplay[selectedJournal + 1].text
	else
		return entry.text
	end
end
function getJournalBackgroundFrame()
	if(journalMode == const.JOURNAL_MODE_QUESTS) then
		return 0
	else
		return 1
	end
end
journalMode = const.JOURNAL_MODE_QUESTS
journalSearchString = ""
`
menu
{
	name 'JOURNAL'
	align left top
	offset 80 0
	ignoreEsc
	enabled "sidebarsGreyed ~= 1"
	onopen "
		reinitQuests()
		buildQuestDisplay()
		chapter = math.max(0,Infinity_GetMaxChapterPage());
	"
	label --background background
	{
		area 0 0 501 773
		mosaic "QUESTBAK"
	}
	label --Background
	{
		area  	0 0 485 747
		bam "QUESTBG"
		sequence 0
		frame lua "getJournalBackgroundFrame()"
	}
	handle
	{
		area 0 0 472 80
		actionDrag
		"
			dragJournal()
		"
	}
	button
	{
		area 216 22 134 34
		text "JOURNAL_LABEL"
		text style "label_parchment"
		text point 16
		action "journalMode = const.JOURNAL_MODE_JOURNAL"
	}
	button
	{
		area 34 18 136 42
		text "QUESTS_LABEL"
		text style "label_parchment"
		text point 16
		action "journalMode = const.JOURNAL_MODE_QUESTS"
	}
	button
	{
		area 419 13 66 67
		on esc
		bam "XBUTT"
		action 
		"
			e:GetActiveEngine():OnLeftPanelButtonClick(2)
		"
	}
	label -- Chapter
	{
		area 85 610 146 60
		text lua "chapterText()"
		text style "label_parchment"
		mosaic "PCHAPTER"
	}
	button --prev chapter
	{
		area		48 610 41 60
		bam "PARROW"
		sequence 0
		
		action
		"
			incrChapter(-1);
		"	
	}
	button
	{
		area		224 610 41 60
		bam "PARROW"
		sequence 1
		
		action
		"
			incrChapter(1);
		"	
	}
	--[Bug #20368] Recent events button cut for now.
	--
	--button
	--{
	--	enabled "journalMode == const.JOURNAL_MODE_QUESTS"
	--	area 278 616 162 47
	--	bam "PAPERBUT"
	--	sequence 1
	--	text "RECENT_EVENTS_LABEL"
	--	text style "button_parchment"
	--	action 
	--	"
	--		Infinity_PushMenu('JOURNAL_RECENT_EVENTS')
	--	"
	--}
	label
	{
		enabled "journalMode == const.JOURNAL_MODE_JOURNAL"
		area 54 88 374 32
		fill 50 50 50 150
	}
	edit
	{
		enabled "journalMode == const.JOURNAL_MODE_JOURNAL"
		area 62 94 357 22
		var journalSearchString
		placeholder "ENTER_SEARCH_TERM_NORMAL"
		text style "edit"
		maxlines 1
	}
	list
	{
		column
		{
			width 10
			label
			{
				area 0 0 31 31
				enabled "getArrowEnabled(rowNumber)"
				bam "PCHEV"
				frame lua "getArrowFrame(rowNumber)"
				text style "label_parchment"
				align top center
			}
		}
		column { 
			width 90 
			label
			{
				enabled "questEnabled(rowNumber)"
				area 0 0 -1 -1
				rectangle 1
				rectangle opacity 150
			}
			label
			{	
				enabled "questEnabled(rowNumber)"
				area 8 0 -1 -1
				text lua "getQuestText(rowNumber)"
				text style "label"
				align left center
			}
			label
			{
				enabled "objectiveEnabled(rowNumber)"
				area 16 0 -1 -1
				pad 0 10 0 10
				text lua "getObjectiveText(rowNumber)"
				text style "normal_parchment"
			}
			label
			{
				enabled "entryEnabled(rowNumber)"
				area 16 0 -1 -1
				pad 0 10 0 10
				text lua "getEntryText(rowNumber)"
				text style "normal_parchment"
				text color M
			}
		}
		enabled "journalMode == const.JOURNAL_MODE_QUESTS"
		rowheight	dynamic
		hidehighlight
		seperator "showObjectiveSeperator(rowNumber)"
		table		"questDisplay"
		var			selectedQuest
		scrollbar	'GUISCRP'
		area		48 98 404 480
		action
		"
			if(questDisplay[selectedQuest].expanded) then 
				questDisplay[selectedQuest].expanded = nil
			else
				questDisplay[selectedQuest].expanded = 1
			end
		"
		
	}
	
	list --journal
	{
		column
		{
			width 100
			--light
			label
			{
				enabled "getJournalTitleEnabled(rowNumber) and not getJournalDarken(rowNumber)"
				area 0 0 -1 -1
				pad 0 16 0 0
				text lua "getJournalTitleText(rowNumber)"
				text style "label_parchment"
				text color 0 120 0 255
			}
			label
			{
				enabled "getJournalEntryEnabled(rowNumber) and not getJournalDarken(rowNumber)"
				area 0 0 -1 -1
				pad 8 16 0 16
				text lua "getJournalEntryText(rowNumber)"
				text style "normal_parchment"
			}
			
			--dark
			label
			{
				enabled "(getJournalTitleEnabled(rowNumber) or getJournalEntryEnabled(rowNumber)) and getJournalDarken(rowNumber)"
				area 0 0 -1 -1
				fill 0 0 0 150
			}
			label
			{
				enabled "getJournalTitleEnabled(rowNumber) and getJournalDarken(rowNumber)"
				area 0 0 -1 -1
				pad 0 16 0 0
				text lua "getJournalTitleText(rowNumber)"
				text style "label_parchment"
				text color 255 100 100 255
			}
			label
			{
				enabled "getJournalEntryEnabled(rowNumber) and getJournalDarken(rowNumber)"
				area 0 0 -1 -1
				pad 8 16 0 16
				text lua "getJournalEntryText(rowNumber)"
				text style "normal_parchment"
				text color 'B'
			}
			
			
		}
		enabled "journalMode == const.JOURNAL_MODE_JOURNAL"
		seperator "getJournalEntryEnabled(rowNumber)"
		rowheight	dynamic
		hidehighlight
		table		"journalDisplay"
		var			selectedJournal
		scrollbar	'GUISCRP'
		area		54 128 386 450
	}
	label
	{
		area 58 569 382 25
		mosaic PAPERSEP
	}
	button
	{
		enabled "journalMode == const.JOURNAL_MODE_JOURNAL"
		area 272 594 162 47
		bam "PAPERBUT"
		sequence 1
		text "ADD_ENTRY_LABEL"
		text style "button_parchment"
		action 
		"
			journalMode = const.JOURNAL_MODE_EDIT
			journalNoteEdit = ''
			journalNoteEditRef = nil
		"
	}
	button
	{
		enabled "journalMode == const.JOURNAL_MODE_JOURNAL"
		clickable lua "journalEntryClickable(selectedJournal)"
		area 272 641 162 47
		bam "PAPERBUT"
		sequence 1
		text "EDIT_ENTRY_LABEL"
		text style "button_parchment"
		action
		"
			journalNoteEditRef = getJournalEntryRef(selectedJournal)
			journalNoteEdit = Infinity_FetchString(journalNoteEditRef)
			journalMode = const.JOURNAL_MODE_EDIT
		"
	}
	
	
	label
	{
		enabled "journalMode == const.JOURNAL_MODE_EDIT"
		area 48 88 392 36
		text style "normal_parchment"
		text "WRITE_ENTRY_TEXT"
		
	}
	label
	{
		enabled "journalMode == const.JOURNAL_MODE_EDIT"
		area 58 140 376 4
		fill 10 71 1 255
	}
	label
	{
		enabled "journalMode == const.JOURNAL_MODE_EDIT"
		area 58 144 382 42
		text style "label"
		text color 0 120 0 255
		text lua "Infinity_GetTimeString()"
	}
	edit
	{
		enabled "journalMode == const.JOURNAL_MODE_EDIT"
		area		58 186 382 383
		text style	"edit_parchment"
		var			journalNoteEdit
		scrollbar	'GUISCRP'
		
	}
	
	button
	{
		enabled "journalMode == const.JOURNAL_MODE_EDIT"
		area 272 641 162 47
		bam "PAPERBUT"
		sequence 1
		text "CANCEL_BUTTON"
		text style "button_parchment"
		action 
		"
			journalMode = const.JOURNAL_MODE_JOURNAL
		"
	}
	button
	{
		enabled "journalMode == const.JOURNAL_MODE_EDIT"
		area 272 594 162 47
		bam "PAPERBUT"
		sequence 1
		text "DONE_BUTTON"
		text style "button_parchment"
		action 
		"
			if(journalNoteEditRef == nil) then
				Infinity_OnAddUserEntry(journalNoteEdit)
			else
				Infinity_OnEditUserEntry(journalNoteEditRef, journalNoteEdit)
			end
			journalMode = const.JOURNAL_MODE_JOURNAL
		"
	}
	
	
}
menu
{
	name 'JOURNAL_RECENT_EVENTS'
	align center center
	modal
	label
	{
		area 0 0 672 672
		mosaic "RECENTEV"
		
	}
	label
	{
		area 158 52 354 46
		text "RECENT_EVENTS_TITLE"
		text style "title"
	}
	button
	{
		area 594 10 33 35
		bam "XBUTT"
		action 
		"
			Infinity_PopMenu('JOURNAL_RECENT_EVENTS')
		"
	}
	text
	{
		area 126 106 422 458
		text "Recent events text will go here."
		text style "normal"
	}
	button
	{ 
		area		320 572 200 44
		text		"DONE_BUTTON"
		text style	'button'
		bam			GUIBUTNT
		sequence	2
		action
		"
			Infinity_PopMenu('JOURNAL_RECENT_EVENTS')
		"
	}
}
`
function processQuestsWithStyle()
	out = ""
	for k,v in pairs(quests_old) do
		local questStrref = v[3]
		out = out .. "createQuest    ( " .. questStrref .. " )\n"
		
		for k2,v2 in pairs(journals_quests_old) do
			if(v2[2] == k) then
				local subgroup = v2[const.ENTRIES_IDX_SUBGROUP]
				if(subgroup == 0) then subgroup = "nil" end
				out = out .. "createEntry    ( " .. questStrref .. ", -1, " .. v2[1] .. ", {}, " .. subgroup .." )\n"
			end
		end
	end
	Infinity_Log(out)
end
`
menu
{
	name 'MESSAGE_SCREEN'
	align center center
	label
	{
		area 0 0 657 234
		mosaic GUIERR6
	}
	label
	{
		area 29 21 580 126
		text lua "Infinity_FetchString(messageScreenText)"
		text style	"label"
	}
}
`
function getDLCDescription()
	return Infinity_FetchString(dlcScreen:GetDLCDescription())
end
function getDLCTitle()
	return Infinity_FetchString(dlcScreen:GetDLCTitle())
end
function getDLCIndex()
	return dlcScreen:GetDLCIndex() .. "/" .. dlcScreen:GetDLCCount()
end
function isDLCBuyButtonClickable()
	local isBought = dlcScreen:GetDLCBought()
	return isBought == false
end
`
menu
{
	name 'START_DLC'
	align center center

	label
	{
		area 0 0 1024 768
		mosaic 'GUIDLC'
	}

	label
	{
		area		60 14 906 42
		text        "STORE_LABEL"
		text style  'title'
		text align	center center
	}

	label
	{
		area		574 582 346 28
		text lua	"getDLCIndex()"
		text style  'title'
		text align	center center
	}

	label
	{
		area		578 162 336 52
		text lua	"getDLCTitle()"
		text style  'title'
		text align	center center
	}
		
	text
	{
		area		578 220 336 362
		text lua	"getDLCDescription()"
		text style  'normal'
		scrollbar	'GUISCRC'		
	}
	
	label
	{
		area 154 98 366 566
		bitmap lua "dlcScreen:GetDLCImage()"
	}

	button 
	{
		bam 'GUIPRC'
		sequence 0
		area 22 274 56 140
		align center center
		action 
		"
			dlcScreen:DecrementDLCIndex()
		"
	}

	button 
	{
		bam 'GUIPRC'
		sequence 1
		area 946 270 52 140
		align center center
		action 
		"
			dlcScreen:IncrementDLCIndex()
		"
	}

	button 
	{
		bam 'GUIOSTUL'
		sequence 0
		area 280 710 240 48
		align center center
		text style "button"
		text "BACK_BUTTON"
		action 
		"
			dlcScreen:OnDoneButtonClick()
		"
	}

	button 
	{
		bam 'GUIOSTCL'
		sequence 0
		area 602 646 302 46
		align center center
		text style "button"
		text "STRREF_GUI_DLC_RESTORE_PURCHASES"
		clickable lua "not e:IsAndroid()"
		action 
		"
			dlcScreen:RestorePurchases()
		"
	}

	button 
	{
		bam 'BUYBUTT'
		sequence 2
		area 530 710 238 48
		align center center
		text style "button"
		text "BUY_BUTTON"
		clickable lua "isDLCBuyButtonClickable()"
		action 
		"
			dlcScreen:OnBuyButtonClick()
		"
	}
}

`
dlcStatusDescriptionText = ""
dlcStatusButtonText = ""
dlcStatusState = 0

DLC_STATE_WAITING = 0
DLC_STATE_IN_PROGRESS = 1
DLC_STATE_SUCCESS = 2
DLC_STATE_FAILED = 3
DLC_STATE_CANCELLED = 4
DLC_STATE_RESTORING_PURCHASES = 5
DLC_STATE_RESTORING_PURCHASES_COMPLETE = 6
DLC_STATE_DOWNLOADING = 7

function checkDLCState()
	dlcStatusState = dlcScreen:GetDLCState()
	if dlcStatusState == DLC_STATE_WAITING then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_WAITING")
		dlcStatusButtonText = t("BACK_BUTTON")
	elseif dlcStatusState == DLC_STATE_IN_PROGRESS then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_IN_PROGRESS")
		dlcStatusButtonText = t("BACK_BUTTON")
	elseif dlcStatusState == DLC_STATE_SUCCESS then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_SUCCESS")
		dlcStatusButtonText = t("CONTINUE_BUTTON")
	elseif dlcStatusState == DLC_STATE_FAILED then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_FAILED")
		dlcStatusButtonText = t("CONTINUE_BUTTON")
	elseif dlcStatusState == DLC_STATE_CANCELLED then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_CANCELLED")
		dlcStatusButtonText = t("CONTINUE_BUTTON")
	elseif dlcStatusState == DLC_STATE_RESTORING_PURCHASES then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_RESTORING_PURCHASES")
		dlcStatusButtonText = t("BACK_BUTTON")
	elseif dlcStatusState == DLC_STATE_RESTORING_PURCHASES_COMPLETE then
		dlcStatusDescriptionText = t("STRREF_GUI_DLC_RESTORING_PURCHASES_COMPLETE")
		dlcStatusButtonText = t("CONTINUE_BUTTON")
	elseif dlcStatusState == DLC_STATE_DOWNLOADING then
		dlcScreen:GetDownloadString()
		dlcStatusButtonText = ""
	else
		dlcStatusDescriptionText = "WAFFLES_Dont Know How We Got Here_WAFFLES"
		dlcStatusButtonText = "WAFFLES_WAFFLES_WAFFLES"
	end
end

function getDLCStatusText()
	checkDLCState()
	return dlcStatusDescriptionText
end
`
menu
{
	name 'START_DLC_STATUS'
	align center center

	label
	{
		area 0 0 408 420
		mosaic 'GUIERR'
	}

	label
	{
		area 86 76 236 84
		text style "label"
		text lua "getDLCStatusText()"
	}

	button 
	{
		bam 'GUIOSTUM'
		sequence 0
		area 104 320 202 46
		align center center
		text style "button"
		text lua "dlcStatusButtonText"
		enabled "dlcStatusState ~= DLC_STATE_DOWNLOADING"
		action 
		"
			dlcScreen:OnErrorButtonClick();
		"
	}
}
`	
	dialogTable = {}
	dialogOverflowTable = {}
	hasDialogResponse = nil
	
	chatboxScrollToBottom = nil
	chatboxScrollTimeLast = 0
	chatboxContentHeight = 0
	chatboxOverflowed = nil
	chatboxJumpToBottom = nil
	
	-- The following two values determine how many item entries can exist.  We trim 
	-- the number of entries to numDialogTrimEntries once it has overflowed that value
	-- by numDialogOverflowLimit.
	numDialogTrimEntries = 512
	numDialogOverflowEntries = numDialogTrimEntries + 128
	
	lastTrimmedContentHeight = 0
	
	function getNumDialogTableEntries()
		local count = 0
		for _ in pairs(dialogTable) do count = count + 1 end
		return count
	end
	
	function trimDialogTableSize()
		local  numTableEntries = getNumDialogTableEntries()
		if (numTableEntries > numDialogOverflowEntries) then
			local numEntriesToRemove = numTableEntries - numDialogTrimEntries
			while (numEntriesToRemove > 0) do
				-- Get our table entry and calculate its size
				local tableEntry = dialogTable[1]
				local delta = Infinity_GetContentHeight(styles.normal.font, w, tableEntry.text, styles.normal.point, 1, styles.normal.useFontZoom) --1 for indent.
				chatboxContentHeight = chatboxContentHeight - delta
				lastTrimmedContentHeight = lastTrimmedContentHeight + delta
					
				table.remove(dialogTable, 1)
				numEntriesToRemove = numEntriesToRemove - 1
			end
		end
	end
	
	function buildResponsesList()

		hasDialogResponse = nil
		dialogResponses = {}
		for k,v in pairs(worldPlayerDialogChoices) do
			if v.marker then
				table.insert(dialogResponses, v)
				hasDialogResponse = 1
			end
		end
	end
	function canShowDialogButton(num)
		-- Show the buttons if we have a response, and the dialog button is not enabled
		return dialogResponses and dialogResponses[num] ~= nil and showDialogButtonChoices()
	end
	
	function addDialogMessage(text,marker,makeTop)
		local tab = {}
		tab.text = text
		tab.marker = marker
		if(marker) then 
			dialogViewMode = nil
			if(text == "") then
				--empty markers are a signal, we shouldn't actually display them.
				if(makeTop == true) then
					--we'll ensure the next line is included in the visible content.
					chatboxContentHeight = 0
				end
				return
			else
				hasDialogResponse = 1
			end
		end
		
		--Calculate running total of dialog content height
		local x,y,w,h = Infinity_GetArea("worldPlayerDialogChoicesList")
		w = w - 18 --account for scrollbar influence on width
		local delta = Infinity_GetContentHeight(styles.normal.font, w, text, styles.normal.point, 1, styles.normal.useFontZoom) --1 for indent.
		chatboxContentHeight = chatboxContentHeight + delta
		
		if(marker and chatboxContentHeight > h) then
			--More to display than we have room for, put the responses in overflow and hide them behind button
			table.insert(dialogOverflowTable,tab)
		else
			table.insert(dialogTable,tab)
		end
		
		if(makeTop == true) then
			--we'll ensure the next line is included in the visible content.
			chatboxContentHeight = 0
		end
		
		trimDialogTableSize()
		
		triggerChatboxScroll()
		
		buildResponsesList()
	end
	function clearDialogResponses()
		for k,v in pairs(dialogTable) do
			if(v.marker) then
				table.remove(dialogTable,k)
				clearDialogResponses()
			end
		end
		hasDialogResponse = nil
		chatboxOverflowed = nil
		chatboxContentHeight = 0
		dialogOverflowTable = {}
	end
	function dialogEntrySelectable(row)
		return (dialogTable[row].marker ~= nil)
	end
	function showDialogButtonChoices()
		return not (not hasDialogResponse or dialogViewMode or #dialogOverflowTable > 0)
	end
	function getResponsePickable()
		return not hasDialogResponse or dialogViewMode or (gameOptions.m_bConfirmDialog == true)
	end
	function getDialogButtonText()
		if(dialogViewMode) then
			return t("DONE_BUTTON")
		end
		
		if(#dialogOverflowTable > 0) then
			return t("SHOW_MORE_RESPONSES_BUTTON")
		end
		
		if(gameOptions.m_bConfirmDialog == true) then
			return t("CHOOSE_RESPONSE_BUTTON")
		end
		
		return dialogButtonText
	end
	function triggerChatboxScroll()
		chatboxScrollToBottom = 1
		chatboxScrollTimeLast = Infinity_GetClockTicks()
	end
	function chatboxScroll(top, height, contentHeight)
		if(chatboxJumpToBottom and contentHeight > height) then
			chatboxJumpToBottom = nil
			return height-contentHeight
		end
		if(chatboxScrollToBottom == 0) then
			--defer to default scrolling
			return nil
		end
		if(contentHeight < height) then
			--no scrolling required, content fits
			chatboxScrollToBottom = nil
			return nil
		end
		local dT = Infinity_GetClockTicks() - chatboxScrollTimeLast
		chatboxScrollTimeLast = Infinity_GetClockTicks()
		top = top + lastTrimmedContentHeight
		lastTrimmedContentHeight = 0
		local newTop = (dT * -0.25) + top
		if (newTop + contentHeight > height + 200) then
			return (height - contentHeight + 200)
		end
		if(newTop + contentHeight < height) then
			chatboxScrollToBottom = 0
			return height - contentHeight
		end
		return newTop
	end
	function displayOverflowResponses()
		for k,v in pairs(dialogOverflowTable) do
			table.insert(dialogTable,v)
		end
		dialogOverflowTable = {}
		triggerChatboxScroll()
		buildResponsesList()
	end
	function GetFirstMarkedResponse()
		for k,v in pairs(dialogTable) do
			if v.marker ~= nil then
				return k
			end
		end
		return -1	
	end
	function onDialogButtonClick()
		if(dialogViewMode) then
			--In dialog view mode this button closes the menu.
			worldScreen:StopDialogHistory()
			return
		end
		
		if(#dialogOverflowTable > 0) then
			displayOverflowResponses()
			return
		end

		if(gameOptions.m_bConfirmDialog == true and hasDialogResponse) then
			-- if confirm dialog and choices available.
			worldScreen:OnDialogReplyClick(dialogTable[worldPlayerDialogSelection].marker)
			worldPlayerDialogSelection = 0
			return
		else
			-- no choices, just step.
			worldScreen:StepDialog()
		end
	end
	function getDialogRowClickable(row)
		return dialogTable[row].marker ~= nil
	end
	function isTouchActionbar()
		--Make this read from an option to make it easy to switch out.
		local default = 0
		if(e:IsTouchUI()) then default = 1 end
		local val = Infinity_GetINIValue('Program Options', 'Use Touch Actionbar', default)
		if (val ~= 0) then
			return 1
		else
			return nil
		end
	end
`
menu
{
	name 'WORLD_DIALOG_LEFT'
	align left center
	ignoreEsc
	--ignoreFocus 1
	onOpen
	"
		Infinity_PushMenu('WORLD_DIALOG_LEFT_BUTTONS')
	"
	onClose
	"
		Infinity_PopMenu('WORLD_DIALOG_LEFT_BUTTONS')
	"
	label
	{
		area 0 0 80 1536
		mosaic GUIWLSP
	}
}
menu
{
	name 'WORLD_DIALOG_LEFT_BUTTONS'
	align left center
	ignoreEsc
	--ignoreFocus 1
	label
	{
		area 0 0 85 780
		rectangle 4
	}
	button
	{
		area 15 25 54 54
		bam CBUTT
		scaleToClip
		text lua "'...'"
		text style "button"
		pad -3 -6 0 0
		enabled "not showDialogButtonChoices()"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			onDialogButtonClick()
		"
	}

	button
	{
		area 15 25 54 54
		bam CBUTT
		scaleToClip
		text lua "'1'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(1)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[1].marker)
		"
	}
	button
	{
		area 15 100 54 54
		bam CBUTT
		scaleToClip
		text lua "'2'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(2)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[2].marker)
		"
	}
	button
	{
		area 15 175 54 54
		bam CBUTT
		scaleToClip
		text lua "'3'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(3)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[3].marker)
		"
	}
	button
	{
		area 15 250 54 54
		bam CBUTT
		scaleToClip
		text lua "'4'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(4)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[4].marker)
		"
	}
	button
	{
		area 15 325 54 54
		bam CBUTT
		scaleToClip
		text lua "'5'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(5)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[5].marker)
		"
	}
	button
	{
		area 15 400 54 54
		bam CBUTT
		scaleToClip
		text lua "'6'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(6)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[6].marker)
		"
	}
	button
	{
		area 15 475 54 54
		bam CBUTT
		scaleToClip
		text lua "'7'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(7)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[7].marker)
		"
	}

	button
	{
		area 15 550 54 54
		bam CBUTT
		scaleToClip
		text lua "'8'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(8)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[8].marker)
		"
	}

	button
	{
		area 15 625 54 54
		bam CBUTT
		scaleToClip
		text lua "'9'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(9)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[9].marker)
		"
	}
	button
	{
		area 15 700 54 54
		bam CBUTT
		scaleToClip
		text lua "'10'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(10)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[10].marker)
		"
	}
}
menu
{
	name 'WORLD_DIALOG_RIGHT'
	align right center
	ignoreEsc
	--ignoreFocus 1
	enabled "canShowDialogButton(11)"
	onOpen
	"
		Infinity_PushMenu('WORLD_DIALOG_RIGHT_BUTTONS')
	"
	onClose
	"
		Infinity_PopMenu('WORLD_DIALOG_RIGHT_BUTTONS')
	"
	label
	{
		area 0 0 80 1536
		mosaic GUIWRSP
	}
}
menu
{
	name 'WORLD_DIALOG_RIGHT_BUTTONS'
	align right center
	ignoreEsc
	--ignoreFocus 1
	enabled "canShowDialogButton(11)"
	label
	{
		area 0 0 85 780
		rectangle 4
	}
	button
	{
		area 15 25 54 54
		bam CBUTT
		scaleToClip
		text lua "'11'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(11)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[11].marker)
		"
	}
	button
	{
		area 15 100 54 54
		bam CBUTT
		scaleToClip
		text lua "'12'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(12)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[12].marker)
		"
	}
	button
	{
		area 15 175 54 54
		bam CBUTT
		scaleToClip
		text lua "'13'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(13)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[13].marker)
		"
	}
	button
	{
		area 15 250 54 54
		bam CBUTT
		scaleToClip
		text lua "'14'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(14)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[14].marker)
		"
	}
	button
	{
		area 15 325 54 54
		bam CBUTT
		scaleToClip
		text lua "'15'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(15)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[15].marker)
		"
	}
	button
	{
		area 15 400 54 54
		bam CBUTT
		scaleToClip
		text lua "'16'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(16)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[16].marker)
		"
	}
	button
	{
		area 15 475 54 54
		bam CBUTT
		scaleToClip
		text lua "'17'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(17)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[17].marker)
		"
	}

	button
	{
		area 15 550 54 54
		bam CBUTT
		scaleToClip
		text lua "'18'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(18)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[18].marker)
		"
	}

	button
	{
		area 15 625 54 54
		bam CBUTT
		scaleToClip
		text lua "'19'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(19)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[19].marker)
		"
	}
	button
	{
		area 15 700 54 54
		bam CBUTT
		scaleToClip
		text lua "'20'"
		text style "button"
		pad -3 -6 0 0
		enabled "canShowDialogButton(20)"
		clickable lua "not dialogEntryGreyed()"
		action
		"
			worldScreen:OnDialogReplyClick(dialogResponses[20].marker)
		"
	}
}
`
	currentButtonHelp = 11
	buttonHelp = 
	{
		{'GUILS10', 	 0,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_RETURNTOGAME'}, 			--  1	return to game
		{'GUILS10', 	 1,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_MAP'}, 					--  2	map
		{'GUILS10', 	 2,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_JOURNAL'},				--  3	journal
		{'GUILS10', 	 3,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_INVENTORY'}, 				--  4	inventory
		{'GUILS10', 	 4,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERRECORD'}, 		--  5	record
		{'GUILS10', 	 5,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_MAGESPELLS'}, 			--  6	mage book
		{'GUILS10', 	 6,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_PRIESTSPELLS'}, 			--  7	priest scroll
		{'GUILS10', 	 7,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_OPTIONS'}, 				--  8	options
		{'GUILS10', 	 8,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERARBITRATION'}, 	--  9	arbitration
		{'GUILS10', 	15,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_QUICKSAVE'}, 				-- 10	quick save
		{'GUILS10', 	16,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_HELP'}, 					-- 11	help
		{'GUILS10', 	 9,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_REST'}, 					-- 12	rest
		{'GUILS10', 	14,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_SELECT'}, 				-- 13	drag
		{'GUILS10', 	11,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_HIGHLIGHT'}, 				-- 14	highlight
		{'GUILS10', 	10,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_TOGGLEAI'}, 				-- 15	ai
		{'GUILS10', 	13,	-1,	0,	0, -1,			'',	'HELPTUTORIAL_SELECTALL'}, 				-- 16	select all
		{'',            -1,	0,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERPORTRAITS'}, 	-- 17	player 1
		{'',            -1,	1,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERPORTRAITS'}, 	-- 18	player 2
		{'',            -1,	2,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERPORTRAITS'}, 	-- 19	player 3
		{'',            -1,	3,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERPORTRAITS'}, 	-- 20	player 4
		{'',            -1,	4,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERPORTRAITS'}, 	-- 21	player 5
		{'',            -1,	5,	0,	0, -1,			'',	'HELPTUTORIAL_CHARACTERPORTRAITS'}, 	-- 22	player 6
		{'',            -1,	-1,	1,	0, -1,			'',	'HELPTUTORIAL_CLOCK'}, 					-- 23	clock
		{'ROUNDBUT',	 0,	-1,	0,	1, -1,			'',	'HELPTUTORIAL_QUICKLOOT'}, 				-- 24	quick loot
		{'GUIBTACT',	64,	-1,	0,	0,  0,			'',	'HELPTUTORIAL_ARROWLEFT'}, 				-- 25
		{'GUIBTACT',	66,	-1,	0,	0,  1,			'',	'HELPTUTORIAL_ARROWRIGHT'}, 			-- 26
		{'GUIBTACT',	22,	-1,	0,	0,  2,			'',	'HELPTUTORIAL_BARDSONG'}, 				-- 27
		{'GUIBTACT',	12,	-1,	0,	0,  3,			'',	'HELPTUTORIAL_CASTSPELLS'}, 			-- 28
		{'GUIBTACT',	34,	-1,	0,	0,  4,			'',	'HELPTUTORIAL_FINDTRAPS'}, 				-- 29
		{'GUIBTACT',	 4,	-1,	0,	0,  5,			'',	'HELPTUTORIAL_DIALOG'}, 				-- 30
		{'GUIBTACT',	20,	-1,	0,	0,  6,			'',	'HELPTUTORIAL_QUICKFORMATION'}, 		-- 31
		{'GUIBTACT',	 0,	-1,	0,	0,  7,			'',	'HELPTUTORIAL_DEFEND'}, 				-- 32
		{'GUIBTACT',	14,	-1,	0,	0,  8,			'',	'HELPTUTORIAL_ATTACK'}, 				-- 33
		{'GUIBTACT',	40,	-1,	0,	0,  9,			'',	'HELPTUTORIAL_SHAPECHANGE'}, 			-- 34
		{'GUIBTACT',	38,	-1,	0,	0, 10,			'',	'HELPTUTORIAL_SPECIALABILITIES'}, 		-- 35
		{'GUIBTACT',	30,	-1,	0,	0, 11,			'',	'HELPTUTORIAL_STEALTH'}, 				-- 36
		{'GUIBTACT',	26,	-1,	0,	0, 12,			'',	'HELPTUTORIAL_THIEVING'}, 				-- 37
		{'GUIBTACT',	 8,	-1,	0,	0, 13,			'',	'HELPTUTORIAL_TURNUNDEAD'}, 			-- 38
		{'GUIBTACT',	18,	-1,	0,	0, 14,			'',	'HELPTUTORIAL_USEITEM'}, 				-- 39
		{'GUIBTACT',	58,	-1,	0,	0, 15,			'',	'HELPTUTORIAL_STOP'}, 					-- 40
		{'GUIBTACT',	20,	-1,	0,	0, 16,			'',	'HELPTUTORIAL_QUICKFORMATION'}, 		-- 41
		{'GUIBTACT',	20,	-1,	0,	0, 17,			'',	'HELPTUTORIAL_QUICKFORMATION'}, 		-- 42
		{'GUIBTACT',	20,	-1,	0,	0, 18,			'',	'HELPTUTORIAL_QUICKFORMATION'}, 		-- 43
		{'GUIBTACT',	20,	-1,	0,	0, 19,			'',	'HELPTUTORIAL_QUICKFORMATION'}, 		-- 44
		{'GUIBTACT',	20,	-1,	0,	0, 20,			'',	'HELPTUTORIAL_QUICKFORMATION'}, 		-- 45
		{'STONSLOT',	-1,	-1,	0,	0, 21,	'STONITEM',	'HELPTUTORIAL_QUICKITEM'}, 				-- 46
		{'STONSLOT',	-1,	-1,	0,	0, 22,	'STONITEM',	'HELPTUTORIAL_QUICKITEM'}, 				-- 47
		{'STONSLOT',	-1,	-1,	0,	0, 23,	'STONITEM',	'HELPTUTORIAL_QUICKITEM'}, 				-- 48
		{'STONSLOT',	12,	-1,	0,	0, 24,	'STONSPEL',	'HELPTUTORIAL_QUICKSPELLS'}, 			-- 49
		{'STONSLOT',	12,	-1,	0,	0, 25,	'STONSPEL',	'HELPTUTORIAL_QUICKSPELLS'}, 			-- 50
		{'STONSLOT',	12,	-1,	0,	0, 26,	'STONSPEL',	'HELPTUTORIAL_QUICKSPELLS'}, 			-- 51
		{'STONSLOT',	-1,	-1,	0,	0, 27,	'STONWEAP',	'HELPTUTORIAL_QUICKWEAPON'}, 			-- 52
		{'STONSLOT',	-1,	-1,	0,	0, 28,	'STONWEAP',	'HELPTUTORIAL_QUICKWEAPON'}, 			-- 53
		{'STONSLOT',	-1,	-1,	0,	0, 29,	'STONWEAP',	'HELPTUTORIAL_QUICKWEAPON'}, 			-- 54
		{'STONSLOT',	-1,	-1,	0,	0, 30,	'STONWEAP',	'HELPTUTORIAL_QUICKWEAPON'}, 			-- 55
		{'STONSLOT',	-1,	-1,	0,	0, 31,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 56
		{'STONSLOT',	-1,	-1,	0,	0, 32,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 57
		{'STONSLOT',	-1,	-1,	0,	0, 33,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 58
		{'STONSLOT',	-1,	-1,	0,	0, 34,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 59
		{'STONSLOT',	-1,	-1,	0,	0, 35,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 60
		{'STONSLOT',	-1,	-1,	0,	0, 36,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 61
		{'STONSLOT',	-1,	-1,	0,	0, 37,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 62
		{'STONSLOT',	-1,	-1,	0,	0, 38,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 63
		{'STONSLOT',	-1,	-1,	0,	0, 39,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 64
		{'STONSLOT',	-1,	-1,	0,	0, 40,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 65
		{'STONSLOT',	-1,	-1,	0,	0, 41,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 66
		{'STONSLOT',	-1,	-1,	0,	0, 42,			'',	'HELPTUTORIAL_CONFIGURATION'}, 			-- 67
		{'STONSLOT',	-1,	-1,	0,	0, 43,			'',	'HELPTUTORIAL_ARROWLEFT'}, 				-- 68
		{'STONSLOT',	-1,	-1,	0,	0, 44,			'',	'HELPTUTORIAL_ARROWRIGHT'}, 			-- 69
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{},
		{'STONSLOT',	-1,	-1,	0,	0, 67,			'',	'HELPTUTORIAL_SWITCHTOMAGE'}, 			-- 91
		{},
		{'STONSLOT',	-1,	-1,	0,	0, 69,			'',	'HELPTUTORIAL_SWITCHTOCLERIC'}, 		-- 93
	}
`
menu
{
	name 'HELP'
	align center center
	ignoreEsc
	onOpen
	"
		currentButtonHelp = 11
		Infinity_PushMenu('LEFT_SIDEBAR_HELP')
		Infinity_PushMenu('RIGHT_SIDEBAR_HELP')
		Infinity_PushMenu('WORLD_ACTIONBAR_HELP')
	"
	onClose
	"
		Infinity_PopMenu('LEFT_SIDEBAR_HELP')
		Infinity_PopMenu('RIGHT_SIDEBAR_HELP')
		Infinity_PopMenu('WORLD_ACTIONBAR_HELP')
	"
	label
	{
		area 0 0 912 244
		mosaic GUIERR7
	}
	label
	{
		enabled "buttonHelp[currentButtonHelp][3] == -1 and buttonHelp[currentButtonHelp][4] == 0 and buttonHelp[currentButtonHelp][5] == 0 and buttonHelp[currentButtonHelp][6] == -1"
		area 34 24 75 54
		bam lua "buttonHelp[currentButtonHelp][1]"
		sequence lua "buttonHelp[currentButtonHelp][2]"
	}
	label
	{
		enabled "buttonHelp[currentButtonHelp][3] == -1 and buttonHelp[currentButtonHelp][4] == 0 and buttonHelp[currentButtonHelp][5] ~= 0 and buttonHelp[currentButtonHelp][6] == -1"
		area 34 24 44 44
		bam lua "buttonHelp[currentButtonHelp][1]"
		sequence lua "buttonHelp[currentButtonHelp][2]"
		scaleToClip
	}
	label
	{
		enabled "buttonHelp[currentButtonHelp][3] == -1 and buttonHelp[currentButtonHelp][4] == 0 and buttonHelp[currentButtonHelp][5] == 0 and buttonHelp[currentButtonHelp][6] ~= -1"
		area 34 24 75 54
		bam lua "buttonHelp[currentButtonHelp][1]"
		frame lua "buttonHelp[currentButtonHelp][2]"
	}
	button
	{
		area 34 24 64 90
		enabled "buttonHelp[currentButtonHelp][3] ~= -1"
		portrait lua "buttonHelp[currentButtonHelp][3]"
	}

	label
	{
		enabled "buttonHelp[currentButtonHelp][4] ~= 0"
		area 29 16 95 120
		bam "CGEAR"
		frame lua "timer:GetCurrentTime() % 24"
	}
	label
	{
		enabled "buttonHelp[currentButtonHelp][4] ~= 0"
		area 29 16 95 120
		bam "CDIAL"
		frame lua "timer:GetCurrentHour() % timer.TIMESCALE_HOUR_PER_DAY"
	}
	label
	{
		enabled "buttonHelp[currentButtonHelp][4] ~= 0"
		area 29 16 95 120
		bam "CPEN"
		frame lua "timer:GetCurrentTime() % 24"
	}

	label
	{
		enabled "buttonHelp[currentButtonHelp][7] ~= ''"
		area 34 24 52 52
		align center center
		bam lua "buttonHelp[currentButtonHelp][7]"
		frame lua "buttonHelp[currentButtonHelp][7]"
	}

	label
	{
		area 124 16 752 112
		text lua "t(buttonHelp[currentButtonHelp][8])"
		text style	"label"
		text align left top
	}
	button
	{
		area 306 164 300 44
		bam GUIOSTCL
		text "DONE_BUTTON"
		text style	"button"
		action 
		"
			Infinity_PopMenu('HELP')
		"
	}
}

menu
{
	name 'LEFT_SIDEBAR_HELP'
	align left top
	ignoreEsc
	onOpen 
	"
		Infinity_PushMenu('LEFT_SIDEBAR_BOTTOM_HELP')
	"
	onClose 
	"
		Infinity_PopMenu('LEFT_SIDEBAR_BOTTOM_HELP')
	"
	label
	{
		name 'leftSidebarBackground'
		area 0 0 80 1536
		mosaic GUIWLSP
	}
	label
	{

		area 0 1536 80 1536
		mosaic GUIWLSP
	}
	button
	{
		area 3 14 73 55
		bam GUILS10
		sequence 0
		tooltip lua "getTooltipWithHotkey(2,16313)"
		glow lua "true"
		action
		"
			currentButtonHelp = 1
		"
	}
	button
	{
		area 3 69 73 55
		bam GUILS10
		sequence 1
		tooltip lua "getTooltipWithHotkey(4,15418)"
		glow lua "true"
		action
		"
			currentButtonHelp = 2
		"
	}
	button
	{
		area 3 124 73 55
		bam GUILS10
		sequence 2
		tooltip lua "getTooltipWithHotkey(3,16308)"
		glow lua "true"
		action
		"
			currentButtonHelp = 3
		"
	}
	button
	{
		area 3 179 73 55
		bam GUILS10
		sequence 3
		tooltip lua "getTooltipWithHotkey(0,16307)"
		glow lua "true"
		action
		"
			currentButtonHelp = 4
		"
	}
	button
	{
		area 3 234 73 55
		bam GUILS10
		sequence 4
		tooltip lua "getTooltipWithHotkey(1,16306)"
		glow lua "true"
		action
		"
			currentButtonHelp = 5
		"
	}
	button
	{
		area 3 289 73 55
		bam GUILS10
		sequence 5
		tooltip lua "getTooltipWithHotkey(5,16309)"
		glow lua "true"
		action
		"
			currentButtonHelp = 6
		"
	}
	button
	{
		area 3 344 73 55
		bam GUILS10
		sequence 6
		tooltip lua "getTooltipWithHotkey(6,14930)"
		glow lua "true"
		action
		"
			currentButtonHelp = 7
		"
	}
	button
	{
		area 3 399 73 55
		bam GUILS10
		sequence 7
		tooltip lua "getTooltipWithHotkey(7,16311)"
		glow lua "true"
		action
		"
			currentButtonHelp = 8
		"
	}
	button
	{
		area 3 454 73 55
		enabled "e:IsMultiplayer()"
		bam GUILS10
		sequence 8
		tooltip lua "getTooltipWithHotkey(8,16312)"
		glow lua "true"
		action
		"
			currentButtonHelp = 9
		"
	}
}
menu
{
	name 'LEFT_SIDEBAR_BOTTOM_HELP'
	align left bottom
	offset 0 -22
	--combined height of these buttons makes a menu with height = 231, menu is placed into lower left. y pos is offset from top of this menu.
	ignoreEsc
	button
	{
		area 3 0 73 55
		enabled "worldScreen == e:GetActiveEngine()"
		bam GUILS10
		sequence 15
		tooltip lua "getTooltipWithHotkey(28,74261)"
		glow lua "true"
		action
		"
			currentButtonHelp = 10
		"
	}
	button
	{
		area 3 56 73 55
		enabled "worldScreen == e:GetActiveEngine()"
		bam GUILS10
		sequence 16
		tooltip lua "Infinity_FetchString(74270)" --"getTooltipWithHotkey(16,74270)"
		glow lua "true"
		action
		"
			currentButtonHelp = 11
		"
	}
	button
	{
		area 3 110 73 55
		bam GUILS10
		sequence 9
		tooltip lua "getTooltipWithHotkey(31,11942)"
		glow lua "true"
		action
		"
			currentButtonHelp = 12
		"
	}
	
	
	--begin clock
	label
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		bam "CGEAR"
		frame lua "timer:GetCurrentTime() % 24"
		useOverlayTint "worldScreen:CheckIfPaused()"
		overlayTint 180 180 180
	}
	label
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		bam "CDIAL"
		frame lua "timer:GetCurrentHour() % timer.TIMESCALE_HOUR_PER_DAY"
		useOverlayTint "worldScreen:CheckIfPaused()"
		overlayTint 180 180 180
	}
	label
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		bam "CPEN"
		frame lua "timer:GetCurrentTime() % 24"
		useOverlayTint "worldScreen:CheckIfPaused()"
		overlayTint 180 180 180
	}
	button
	{
		enabled "worldScreen == e:GetActiveEngine()"
		area 0 182 73 55
		tooltip lua "worldScreen:GetCurrentTimeString()"
		glow lua "true"
		action
		"
			currentButtonHelp = 23
		"
	}
	--end clock
	label
	{
		--area is preset
		enabled "gameOptions.m_bRenderFrameTimes"
		frameTimes
	}
}

menu
{
	name 'RIGHT_SIDEBAR_HELP'
	align right top
	ignoreEsc
	onOpen
	"
		Infinity_PushMenu('RIGHT_SIDEBAR_BOTTOM_HELP')
	"
	onClose
	"
		Infinity_PopMenu('RIGHT_SIDEBAR_BOTTOM_HELP')
	"
	label
	{
		name 'rightSidebarBackground'
		area 0 0 80 1536
		mosaic GUIWRSP
	}
	label
	{
		area 0 1536 80 1536
		mosaic GUIWRSP
	}
	button
	{
		area 11 14 64 90
		portrait 0
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 0"
		glow lua "true"
		action
		"
			currentButtonHelp = 17
		"
		tooltip lua "Infinity_GetPortraitTooltip(0)"
	}
	button
	{
		area 11 106 64 90
		portrait 1
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 1"
		glow lua "true"
		action
		"
			currentButtonHelp = 18
		"
		tooltip lua "Infinity_GetPortraitTooltip(1)"
	}
	button
	{
		area 11 198 64 90
		portrait 2
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 2"
		glow lua "true"
		action
		"
			currentButtonHelp = 19
		"
		tooltip lua "Infinity_GetPortraitTooltip(2)"
	}
	button
	{
		area 11 290 64 90
		portrait 3
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 3"
		glow lua "true"
		action
		"
			currentButtonHelp = 20
		"
		tooltip lua "Infinity_GetPortraitTooltip(3)"
	}
	button
	{
		area 11 382 64 90
		portrait 4
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 4"
		glow lua "true"
		action
		"
			currentButtonHelp = 21
		"
		tooltip lua "Infinity_GetPortraitTooltip(4)"
	}
	button
	{
		area 11 474 64 90
		portrait 5
		bam GUIRSP10
		enabled "Infinity_GetNumCharacters() > 5"
		glow lua "true"
		action
		"
			currentButtonHelp = 22
		"
		tooltip lua "Infinity_GetPortraitTooltip(5)"
	}
}
menu
{
	name 'RIGHT_SIDEBAR_BOTTOM_HELP'
	align right bottom
	ignoreEsc
	--Buttons form a menu aligned bottom right, with height = 197, y is offset from top of that menu.
	button
	{
		area 6 0 71 48
		enabled "e:IsTouchUI() and worldScreen == e:GetActiveEngine()"
		bam GUILS10
		sequence 14
		glow lua "true"
		tooltip lua "Infinity_FetchString(11942)"
		action
		"
			currentButtonHelp = 13
		"
	}
	button
	{
		area 6 49 71 48
		enabled "worldScreen == e:GetActiveEngine()"
		tooltip lua "Infinity_FetchString(103144)"
		bam GUILS10
		sequence 11
		glow lua "true"
		action
		"
			currentButtonHelp = 14
		"
	}
	button
	{
		area 6 99 71 48
		enabled "worldScreen == e:GetActiveEngine()"
		tooltip lua "getPartyAITooltip()"
		bam GUILS10
		sequence 10
		glow lua "true"
		action
		"
			currentButtonHelp = 15
		"
	}
	button
	{
		area 6 149 71 48
		enabled "worldScreen == e:GetActiveEngine()"
		tooltip lua "Infinity_FetchString(10485)"
		bam GUILS10
		sequence 13
		glow lua "true"
		action
		"
			currentButtonHelp = 16
		"
	}
}
menu
{
	name "WORLD_ACTIONBAR_HELP"
	align center bottom
	onOpen 
	"
	"
	onClose 
	"
	"
	ignoreEsc
	label
	{
		area 0 0 746 57
		mosaic GUWBTP10
	}
	button
	{
		area 21 12 32 32
		bam ROUNDBUT
		glow lua "true"
		scaleToClip
		action
		"
			currentButtonHelp = 24
		"
	}
	button
	{
		area 68 1 52 52
		actionBar 0
		enabled "buttonArray:GetButtonEnabled(0)"
		tooltip lua "actionBarTooltip[0]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(0)
		"
	}
	button
	{
		area 122 1 52 52
		actionBar 1
		enabled "buttonArray:GetButtonEnabled(1)"
		tooltip lua "actionBarTooltip[1]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(1)
		"
	}
	button
	{
		area 177 1 52 52
		actionBar 2
		enabled "buttonArray:GetButtonEnabled(2)"
		tooltip lua "actionBarTooltip[2]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(2)
		"
	}
	button
	{
		area 231 1 52 52
		actionBar 3
		enabled "buttonArray:GetButtonEnabled(3)"
		tooltip lua "actionBarTooltip[3]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(3)
		"
	}
	button
	{
		area 299 1 52 52
		actionBar 4
		enabled "buttonArray:GetButtonEnabled(4)"
		tooltip lua "actionBarTooltip[4]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(4)
		"
	}
	button
	{
		area 353 1 52 52
		actionBar 5
		enabled "buttonArray:GetButtonEnabled(5)"
		tooltip lua "actionBarTooltip[5]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(5)
		"
	}
	button
	{
		area 407 1 52 52
		actionBar 6
		enabled "buttonArray:GetButtonEnabled(6)"
		tooltip lua "actionBarTooltip[6]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(6)
		"
	}
	button
	{
		area 461 1 52 52
		actionBar 7
		enabled "buttonArray:GetButtonEnabled(7)"
		tooltip lua "actionBarTooltip[7]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(7)
		"
	}
	
	button
	{
		area 528 1 52 52
		actionBar 8
		enabled "buttonArray:GetButtonEnabled(8)"
		tooltip lua "actionBarTooltip[8]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(8)
		"
	}
	button
	{
		area 582 1 52 52
		actionBar 9
		enabled "buttonArray:GetButtonEnabled(9)"
		tooltip lua "actionBarTooltip[9]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(9)
		"
	}
	button
	{
		area 636 1 52 52
		actionBar 10
		enabled "buttonArray:GetButtonEnabled(10)"
		tooltip lua "actionBarTooltip[10]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(10)
		"
	}
	button
	{
		area 689 1 52 52
		actionBar 11
		enabled "buttonArray:GetButtonEnabled(11)"
		tooltip lua "actionBarTooltip[11]"
		glow lua "true"
		action
		"
			currentButtonHelp = 25 + buttonArray:GetButtonType(11)
		"
	}
}

