The area was a site of a border fort of the medieval Polish state. During the reign of Bolesław III Wrymouth it was raised to the rank of a castellany. During the period of feudal fragmentation of Poland it was initially part of the Duchy of Greater Poland and then subject of fighting between the Duchy and the Margraviate of Brandenburg, which took control of it after 1296. It was sold by the Brandenburgians to the Monastic Order of the Teutonic Knights in 1317, under the authority of the knights Burkhard and Heinrich von der Osten. However, in 1365 it became part of the Kingdom of Poland, during the rule of King Casimir III the Great, to be lost again to the Teutonic Knights in 1408. The town was neglected by the Teutonic Knights, the castle burned down, and parts of the town walls collapsed. In 1455, after the Thirteen Years' War broke out, the Knights sold it back to Brandenburg in order to raise funds for war against Poland. Polish King Casimir IV Jagiellon still made peaceful efforts to regain the city, but to no avail.