function Building(kind, x, y, upgrade, level)
{
  this.x = x;
  this.y = y;
  this.kind = kind;
  this.level = level;
  this.upgrade = upgrade;
  if(this.kind=="hut")
  {
    this.width = function (){return 1;}
    this.length = function (){return 1;}
  }
  else if(this.kind=="altar")
  {
    this.width = function (){return 1;}
    this.length = function (){return 1;}
  }
  else if(this.kind=="well")
  {
    this.width = function (){return 1;}
    this.length = function (){return 1;}
  }
  else if(this.kind=="cottage")
  {
    this.width = function (){return 2;}
    this.length = function (){return 1;}
  }
  else if(this.kind=="sawmill")
  {
    this.width = function (){return 2;}
    this.length = function (){return 2;}
  }
  else if(this.kind=="granary")
  {
    this.width = function (){return 2;}
    this.length = function (){return 2;}
  }
  else if(this.kind=="store")
  {
    this.width = function (){return 2;}
    this.length = function (){return 2;}
  }
  else if(this.kind=="watchtower")
  {
    this.width = function (){return 2;}
    this.length = function (){return 2;}
  }
  else if(this.kind=="inn")
  {
    this.width = function (){return 1;}
    this.length = function (){return 2;}
  }
  else if(this.kind=="ashes")
  {
    this.width = function (){return 1;}
    this.length = function (){return 1;}
  }
  else if(this.kind=="townHall")
  {
    this.width = function (){return 2;}
    this.length = function (){return 2;}
  }
  this.image = function()
  {
    if(this.upgrade != 0)
    {
      return this.kind + "_uc.png";
    }
    return this.kind + ".png";
  }
}

function setCurrentBuilding(building)
{
  if(document.currentBuilding != undefined)
  {
    cellTag = document.getElementById("cell_"+document.currentBuilding.x+"_"+document.currentBuilding.y);
    if(cellTag != null && (imgTag = cellTag.getElementsByTagName('img')[0]) != undefined)
    {
        imgTag.border = '0';
    }
  }

  document.currentBuilding = building;

  cellTag = document.getElementById("cell_"+building.x+"_"+building.y);
  if(cellTag != null && (imgTag = cellTag.getElementsByTagName('img')[0]) != undefined)
  {
    imgTag.border = '1';
  }

  var loc = document.location.toString();
  if(loc.charAt(loc.length-1) == '#')
  {
    loc = loc.substring(0, loc.length-1);
  }
  go(loc + '/' + building.kind+'/:1', 'buildingDescription');
}

function go(target, box)
{
  if(document.analysis != undefined)
  {
    pageTracker._trackPageview(target); 
  }
  box = document.getElementById(box);
  if(box == null)
  {
      return;
  }
  AJAX.get({
      url: target
    , onInitialization: function() 
        {
            box.innerHTML = "Loading...";
        }
    , onSuccess: function(result) 
        {
            box.innerHTML = result.responseText;
            refresh();
        }
  });
  return false;
}

function goImage(target, box, text, textTarget)
{
    img=document.getElementById(box);
    img.src=target;
    img.style.display='inline';

    textElement=document.getElementById(textTarget);
    textElement.innerHTML=text;
}

function refresh()
{
  building = document.currentBuilding;
  if(building != undefined)
  {
      var upgradeTag = document.getElementById(building.kind + "UpgradeLevel");
      if(upgradeTag != null)
      {
        upgradeTag.innerHTML = "(+"+building.upgrade+")";
      }
      var levelTag = document.getElementById(building.kind + "Level");
      if(levelTag != null)
      {
        levelTag.innerHTML = building.level;
      }
  }

  if(document.loaded == 1)
  {
    return;
  }
  document.loaded = 1;
  startCounter();
  var mapForm = document.forms["mapForm"];

  if(mapForm==null)
  {
    return;
  }
  var buildings = mapForm.buildingsList;
  if(buildings!=null)
  {
    document.map = [];
    for(i = 0;i < 12; ++i)
    {
      document.map[i] = [];
      for(j = 0;j < 12; ++j)
      {
        document.map[i][j] = null;
      }
    }
    buildings = buildings.value;
    buildings = buildings.split(":");
    var buildingsList = new Array();
    for(b in buildings)
    {
      fields = buildings[b];
      fields = fields.split(";");
      var building = new function(){};
      for(field in fields)
      {
        field = fields[field].split("=");
        key = field[0];
        val = field[1];
        building[key]=val;
      }
      buildingsList.push(building);
    }

    for(i in buildingsList)
    {
      with(buildingsList[i])
      {
        var cell = document.getElementById("cell_"+x+"_"+y);
        var building = new Building(kind, parseInt(x), parseInt(y), upgrade, level);
        putBuilding(cell, building);
      }
    }
    document.mapWidth = mapForm.width.value;
    document.mapLength = mapForm.length.value;
    setCurrentBuilding(new Building("hut", -1, -1, 1, 0));//FIXME
  }
}

function putBuilding(cell, building)
{
  for(i = 0; i < building.width(); i++)
  {
    for(j = 0; j < building.length(); j++)
    {
      document.map[building.x+i][building.y+j] = building;
    }
  }
  cell.innerHTML='<div class="mapCell"><a href="#" onclick="javascript: setCurrentBuilding(new Building(\''+building.kind+'\', '+building.x+', '+building.y+', '+building.upgrade+','+building.level+'))"><img style="position:absolute;border-color:red;" border="0" src="/files1/'+building.image()+'" /></a></div>';
}

function checkField(x, y, building)
{
  if(x+document.currentBuilding.width() > document.mapWidth || y+document.currentBuilding.length() > document.mapLength)
  {
    return false;
  }
  for(i = 0; i < document.currentBuilding.width(); i++)
  {
    for(j = 0; j < document.currentBuilding.length(); j++)
    {
      if(document.map[x+i][y+j] != null)
      {
        return false;
      }
    }
  }
  return true;
}

function over(cell)
{
  var xy = cell.split("_");
  var x = parseInt(xy[1]);
  var y = parseInt(xy[2]);
  if(! checkField(x, y) || document.currentBuilding==null)
  {
    return;
  }
  //alert(document.currentBuilding.width() + " " + document.currentBuilding.length());
  for(i = 0; i < document.currentBuilding.width(); i++)
  {
    for(j = 0; j < document.currentBuilding.length(); j++)
    {
      td = document.getElementById("cell_"+(x+i)+"_"+(y+j));
      td.style.backgroundImage = "url(/files1/grass_over.png)";
    }
  }
}

function upgradeCurrentBuilding()
{
    var form = document.forms['upgradeForm'];
    form.x.value = document.currentBuilding.x;
    form.y.value = document.currentBuilding.y;
    form.submit();
}

function destroyCurrentBuilding()
{
    if(document.currentBuilding.x < 0)
    {
        return;
    }
    var form = document.forms['destroyForm'];
    form.x.value = document.currentBuilding.x;
    form.y.value = document.currentBuilding.y;
    form.submit();
}

function out(cell)
{
  var xy = cell.split("_");
  var x = parseInt(xy[1]);
  var y = parseInt(xy[2]);
  for(i = 0; i < document.currentBuilding.width(); i++)
  {
    for(j = 0; j < document.currentBuilding.length(); j++)
    {
      td = document.getElementById("cell_"+(x+i)+"_"+(y+j));
      td.style.backgroundImage = "url(/files1/grass.png)";
    }
  }
}

function click1(cell)
{
  var xy = cell.split("_");
  var x = parseInt(xy[1]);
  var y = parseInt(xy[2]);
  if(! checkField(x, y))
  {
    return;
  }
  cell = document.getElementById(cell);
  document.currentBuilding.x = x;
  document.currentBuilding.y = y;
  putBuilding(cell, document.currentBuilding);
  var newBuildings = document.forms['mapForm'].newBuildings;
  if(newBuildings.value!="")
  {
    newBuildings.value+= ":";
  }
  else
  {
    newBuildings.value = '@';
  }
  newBuildings.value+= "kind="+document.currentBuilding.kind+";x="+x+";y="+y;
}

function registerFormValidate(form)
{
  if(form.password.value != form.confirmedPassword.value)
  {
    alert("password does not match");
    form.password.focus();
    return false;
  }
  return true;
}
function submitForm(form)
{
  form.submit();
}
function startCounter()
{
  if(document.timer != undefined)
  {
    clearInterval(document.timer);
  }
  document.timer = setInterval(
  function()
  {
    var remainingTimeTag = document.getElementById("remainingTime");
    if(remainingTimeTag==null)
    {
      return;
    }
    var i = remainingTimeTag.innerHTML;
    i = parseInt(i);
    if( i-- )
    {
      document.getElementById("remainingTime").innerHTML = i;
      return;
    }
    clearInterval(document.timer);
    go('/user/Town/resources/:1', 'resources');
    go('/user/Town/messages/:1', '/user/Town/messages');
    startCounter();
  }
  , 1000);
}


