local I = {}

function I.close ()
	gGUI.scheduleForDeletion(I.window.instance())
	UI.Interfaces["sailout_towns"] = nil
	I = nil

	if UI.Interfaces["sailout"] ~= nil then
		UI.Interfaces["sailout"].close()
	end
end

function I.create ()

	I.window = LuaWindow(gGUI.createWindow({
    id = "sailTWnd",
		width = 130,
		height = 100,
		verticalAlignment = VerticalAlignment.Middle,
		title = "%title_destination"
	}))

  I.list = LuaList(gGUI.createList({
    parent = I.window.instance(),
    x = 7,
    y = 20,
    width = 116,
    visibleRows = 5,
    showSelection = false,
    rowHeight = 14
  }))

  I.list.onItemSelected(function(index, item)
    item = LuaListDataItem(item)
    gTravelScreen.setTravelCost(0)
    gTravelScreen.setDestinationId(item.iValue1())
    gTravelScreen.setDestinationName(item.title())
    I.close()
    gGUI.doScreenTransition({id = ConstBeginTravelToTownTransition, delay = 0.1})
  end)

	local closeButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = (I.window.getWidth() / 2) - 45,
		y = I.window.getHeight() - 13,
		width = 90,
		height = 18,
		title = "%close_button"
	}))

	closeButton.onClick(function()
  	gGUI.scheduleForDeletion(I.window.instance())
    UI.Interfaces["sailout_towns"] = nil
    I = nil
  end)

  I.populate()

end

function I.populate ()

  local listDataSource = LuaListDataSource(I.list.getDataSource())

  listDataSource.removeAllItems()

  if gGame.getState() == GameState.Town then
    -- Marciudad
    if Town.getCurrentTownIndex() == 0 then
      listDataSource.addItem({ key = "town2", iValue1 = 1, accessoryType = ListRowAccessory.DisclosureDark})
      listDataSource.addItem({ key = "town3", iValue1 = 2, accessoryType = ListRowAccessory.DisclosureDark})
    -- Reval
    elseif Town.getCurrentTownIndex() == 1 then
      listDataSource.addItem({ key = "town1", iValue1 = 0, accessoryType = ListRowAccessory.DisclosureDark})
      listDataSource.addItem({ key = "town3", iValue1 = 2, accessoryType = ListRowAccessory.DisclosureDark})
    -- Oldden
    elseif Town.getCurrentTownIndex() == 2 then
      listDataSource.addItem({ key = "town1", iValue1 = 0, accessoryType = ListRowAccessory.DisclosureDark})
      listDataSource.addItem({ key = "town2", iValue1 = 1, accessoryType = ListRowAccessory.DisclosureDark})
    end
  else
    listDataSource.addItem({ key = "town1", iValue1 = 0, accessoryType = ListRowAccessory.DisclosureDark})
    listDataSource.addItem({ key = "town2", iValue1 = 1, accessoryType = ListRowAccessory.DisclosureDark})
    listDataSource.addItem({ key = "town3", iValue1 = 2, accessoryType = ListRowAccessory.DisclosureDark})
  end

end

UI.Interfaces["sailout_towns"] = I
