/**
 * Javascript that makes the map magic work... 
 * ADJ: 080825
 *
 * expect a few variable to be set already...
 * travian_server = server url 
 * map_size = size of map 
 * alliance_confed = array of confed alliance
 * alliance_nap = array of nap alliances
 * alliance_war = array of war alliances
 * player_uid = player uid
 * show_idle = should render show idle players
 * map_click = where does map click lead
 * offsetX = left offset of map
 * offsetY = top offset of map
 **/

// positions of things in the map_data array
var ALLIANCE = 0;
var AID = 1;
var PLAYER = 2;
var UID = 3;
var RACE = 4;
var VILLAGE = 5;
var VID = 6;
var POP = 7;
var IDLE = 8;
var TID = 9;
var TILE = 10;

// current x and y coords travian world
var current_x = 0;
var current_y = 0;

// current x and y coords of map (0,0) - (7,7)
var coord_x = 0;
var coord_y = 0;

// map data contained here
var map_data = new Array();

// last click x, y of travian world
var click_x = 0;
var click_y = 0;

function rightClickEvent() { this.button = 3; }

document.oncontextmenu = function() { 
  if (IE) 
    document.onclick(new rightClickEvent());

  return false; 
};

document.onclick = function(e) {
  // right click 
  var elem = document.getElementById("click_menu");
  if (elem == null) return;

  // compatability madness!
  if ((IE && e && e.button == 3) || 
      (IE && event.button == 3) || 
      (!IE && e.which == 3)) {
    elem.style.visibility = "visible";
    elem.style.top = tempY;
    elem.style.left = tempX; 
  } else {
    elem.style.visibility = "hidden";
  }
};

function mapClick(c) {
  sid = getCookie("sid");

  /**
  var my_x = click_x;
  var my_y = click_y;
  var pos_x, pos_y;

  // shift original 
  my_x -= (offset_x + 14);
  my_y -= (offset_y - 2);

  // rotate
  pos_x = Math.cos(Math.PI / 3) * my_x / 20 + Math.sin(Math.PI / 6) * my_y / 36; 
  pos_y = -1 * Math.sin(Math.PI / 6) * my_x / 20 + Math.cos(Math.PI / 3) * my_y / 36;

  // shift final 
  pos_x = Math.floor(pos_x) - 10;
  pos_y = Math.floor(pos_y * -1);

  // translate to map coord
  pos_x = current_x + pos_x - 7; 
  pos_y = current_y + (7 - pos_y);
**/

  switch (c) {
   case 1:
     index = (map_size * coord_y) + coord_x;
     page = "/player.php?uid=" + map_data[index][UID] + "&change_sid=" + sid;
     popUp(page, 900, 500);
     break;
   case 2:
     index = (map_size * coord_y) + coord_x;
     page = travian_server + "spieler.php?uid=" + map_data[index][UID];
     popUp(page, 900, 500);
     break;
   case 3:
     loadMap(click_x, click_y); 
     break;
   case 4:
     page = travian_server + "karte.php?xp=" + click_x + "&yp=" + click_y;
     popUp(page, 900, 500);
     break;
   case 5:
     map_id = (click_x + 400) + (400 - click_y) * 801 + 1;
     page = travian_server + "a2b.php?z=" + map_id;
     popUp(page, 900, 500);
     break;
  }  

}

function updateClick() {
  var act = document.advanced.click_action;
  map_click = act[act.selectedIndex].value;
  setCookie("map_click", map_click, 7);
}

function saveAdvanced() {
  sid = getCookie("sid");

  player = document.advanced.player.value;
  setCookie("player" + sid, player, 7);
  confed = alliance_confed.join(",");
  setCookie("alliance_confed" + sid, confed, 7);
  nap = alliance_nap.join(",");
  setCookie("alliance_nap" + sid, nap, 7);
  war = alliance_war.join(",");
  setCookie("alliance_war" + sid, war, 7);
}

function clearAdvanced() {
  if (!confirm("Are you sure you want to clear all settings?"))
    return;

  // clear arrays
  elem = findElement(document.advanced, "aid1" + "[]");
  for (x=0; x<elem.length; x++)
    elem[x].selected = false;
  elem = findElement(document.advanced, "aid2" + "[]");
  for (x=0; x<elem.length; x++)
    elem[x].selected = false;
  elem = findElement(document.advanced, "aid3" + "[]");
  for (x=0; x<elem.length; x++)
    elem[x].selected = false;
  document.advanced.player.value = "";
  
  // clear cookies
  sid = getCookie("sid");
  setCookie("alliance_confed" + sid, "", 7);
  setCookie("alliance_nap" + sid, "", 7);
  setCookie("alliance_war" + sid, "", 7);
  setCookie("player" + sid, "", 7);
}

function updateAdvanced() {
  temp_arr = new Array();
  elem = findElement(document.advanced, "aid1" + "[]");
  for (x=0; x<elem.length; x++)
    if (elem[x].selected)
      temp_arr.push(elem[x].value);
  temp_arr = "[" + temp_arr.join(",") + "];";
  eval("alliance_confed = " + temp_arr);

  temp_arr = new Array();
  elem = findElement(document.advanced, "aid2" + "[]");
  for (x=0; x<elem.length; x++)
    if (elem[x].selected)
      temp_arr.push(elem[x].value);
  temp_arr = "[" + temp_arr.join(",") + "];";
  eval("alliance_nap = " + temp_arr);

  temp_arr = new Array();
  elem = findElement(document.advanced, "aid3" + "[]");
  for (x=0; x<elem.length; x++)
    if (elem[x].selected)
      temp_arr.push(elem[x].value);
  temp_arr = "[" + temp_arr.join(",") + "];";
  eval("alliance_war = " + temp_arr);

  saveAdvanced();
  renderMap();
}

function viewTile(x, y) {
  sid = getCookie("sid");
  index = (y * map_size) + x;
  x = x - Math.floor(map_size / 2) + current_x;
  y = (map_size - y - 1) - Math.floor(map_size / 2) + current_y;

  if (map_click == 2) {
    uid = map_data[index][UID];
    url = travian_server + "spieler.php?uid=" + uid;
    window.open(url);
    return;
  }

  if (map_click == 3) {
    loadMap(x, y);
    return;
  }

  if (map_click == 4) {
    uid = map_data[index][UID];
    url = travian_server + "karte.php?xp=" + x + "&yp=" + y;
    window.open(url);
    return;
  }

  if (map_click == 5) {
    map_id = (x + 400) + (400 - y) * 801 + 1;
    page = travian_server + "a2b.php?z=" + map_id;
    window.open(page);
    return;
  }

  url  = "./player.php?change_sid=" + sid + "&x=";
  url += x + "&y=" + y;
  location.href = url;
}

function flipIdle() {
  show_idle = (show_idle == 0) ? 1 : 0;
  document.myform.show_idle.value = show_idle;
  renderMap();

  // update controls
  html = document.getElementById("control").innerHTML;
  if (show_idle == 0) 
    eval('html = html.replace(/' + show + '/, "' + hide + '");');
  if (show_idle == 1) 
    eval('html = html.replace(/' + hide + '/, "' + show + '");');
  document.getElementById("control").innerHTML = html;
}

function flipAdvanced() {
  show_advanced = (show_advanced) ? 0 : 1; 

  elem = document.getElementById("advanced_options");
  if (show_advanced == 0) 
    elem.style.visibility = "hidden";
  if (show_advanced == 1)
    elem.style.visibility = "visible";
}

function get_city(pop, mod) {
  if (pop >= 500)
    return "./images/map/city_large_" + mod + ".gif";
  if (pop >= 250)
    return "./images/map/city_medium_" + mod + ".gif";
  if (pop >= 100)
    return "./images/map/city_small_" + mod + ".gif";
 
  return "./images/map/city_tiny_" + mod + ".gif";
}

function get_world(x, y, tile) {
  if (tile == 7)
    return "./images/map/oasis_w1.gif"; 
  if (tile == 8)
    return "./images/map/oasis_c1.gif"; 
  if (tile == 9)
    return "./images/map/oasis_i1.gif"; 
  if (tile == 10)
    return "./images/map/oasis_r2.gif"; 
  if (tile == 11)
    return "./images/map/oasis_rr.gif"; 
  if (tile == 12)
    return "./images/map/oasis_wr.gif"; 
  if (tile == 13)
    return "./images/map/oasis_cr.gif"; 
  if (tile == 14)
    return "./images/map/oasis_ir.gif"; 

  // default
  tile = Math.abs((x * y) % 9);
  return "./images/map/t" + tile + ".gif";
}

var cache = new Array();

function in_cache(x, y) {
  for (i=0; i<cache.length; i++) 
    if (cache[i][0] == x && cache[i][1] == y)
      return true;

  return false;
}

function cache_lookup(x, y) {
  for (i=0; i<cache.length; i++)
    if (cache[i][0] == x && cache[i][1] == y)
      return cache[i][2];

  return 0;
}

function add_cache(x, y, data) {
  cache.push(new Array(x, y, data));
  while (cache.length > 64) /* this seems reasonable */
    cache.shift(); /* keep most recent */
}

function shiftMap(dx, dy) {
  loadMap(current_x + dx, current_y + dy);
}

function renderMap() {
  // render coords
  for (x=0; x<map_size; x++) {
    coord = document.getElementById("pos_" + x + "_" + map_size);
    if (coord)
      coord.innerHTML = '<FONT STYLE="font-size: 8pt;">' + (x + current_x - 7) + '</FONT>';
  }

  for (y=0; y<map_size; y++) {
    coord = document.getElementById("pos_" + map_size + "_" + y);
    if (coord)
      coord.innerHTML = '<FONT STYLE="font-size: 8pt;">' + ((7 - y) + current_y) + '</FONT>';
  }

  // render map data
  for (x=0; x<map_size; x++)
    for (y=0; y<map_size; y++) {
      tile = document.getElementById("tile_" + x + "_" + y);
      index = (y * map_size) + x;

      mod = "other";
      mod = (map_data[index][IDLE] > 0 && show_idle == 1) ? "gray" : mod;
      if (alliance_confed.contains(map_data[index][AID]))
        mod = "ally";
      if (alliance_nap.contains(map_data[index][AID]))
        mod = "nap";
      if (alliance_war.contains(map_data[index][AID]))
        mod = "enemy"; 
      if (map_data[index][UID] == player_uid)
	mod = "self";

      // ordering goes here... 
      if (tile)
      tile.src = (map_data[index][VID] == "") ? 
	get_world(current_x + x, current_y - y, map_data[index][TILE]) : 
	get_city(map_data[index][POP], mod);
    }

  // YYY: later optimize to only load necessary data (i.e. one row)
}

function loadMap(x, y) {
  x *= 1; // cast integer
  y *= 1; // cast integer
  // cookies expire in 7 days
  setCookie("last_x", x, 7);
  setCookie("last_y", y, 7);

  // cache lookup
  if (in_cache(x, y)) { /* gets us sub 100ms refresh... bout 4-8 savings depending on RTT */
    map_data = cache_lookup(x, y);
  } else {
    // create url to get map data
    request  = base + "map_manager.php?map_size=" + escape(map_size);
    request += "&act=map_data&pos_x=" + escape(x) + "&pos_y=" + escape(y);
    result = HttpRequest(request);    
    eval("map_data = " + result + ";");

    // cache our data
    add_cache(x, y, map_data);
  }

  // set the coords
  setCoords(x, y);

  // modify our global positions
  document.myform.pos_x.value = current_x = x;
  document.myform.pos_y.value = current_y = y;

  // render map just uses the newly loaded map data
  renderMap();
}

function tile2info(type) {
  crop = '<IMG SRC="/images/crop.gif">';
  clay = '<IMG SRC="/images/clay.gif">';
  iron = '<IMG SRC="/images/iron.gif">';
  wood = '<IMG SRC="/images/wood.gif">';

  if (type == 1)  
     return "4 " + wood + " 4 " + clay + " 4 " + iron + " 6 " + crop; 
  if (type == 2)     
     return "4 " + wood + " 5 " + clay + " 3 " + iron + " 6 " + crop;
  if (type == 3)
     return "5 " + wood + " 3 " + clay + " 4 " + iron + " 6 " + crop; 
  if (type == 4)
     return "3 " + wood + " 4 " + clay + " 5 " + iron + " 6 " + crop; 
  if (type == 5)     
     return "3 " + wood + " 3 " + clay + " 3 " + iron + " 9 " + crop;
  if (type == 6)
     return "1 " + wood + " 1 " + clay + " 1 " + iron + " 15 " + crop;
  if (type == 7)
     return wood + "+25%"; 
  if (type == 8)
     return clay + "+25%"; 
  if (type == 9)
     return iron + "+25%"; 
  if (type == 10)
     return crop + "+25%"; 
  if (type == 11)
     return crop + "+50%"; 
  if (type == 12)
     return wood + "+25% " + crop + "+25%"; 
  if (type == 13)
     return clay + "+25% " + crop + "+25%"; 
  if (type == 14)
     return iron + "+25% " + crop + "+25%"; 

  if (type == 30)
    return "3 " + wood + " 5 " + clay + " 4 " + iron + " 6 " + crop;
  if (type == 31)
    return "5 " + wood + " 4 " + clay + " 3 " + iron + " 6 " + crop;
  if (type == 32)
    return "4 " + wood + " 3 " + clay + " 5 " + iron + " 6 " + crop;

  if (type == 33)
    return "3 " + wood + " 4 " + clay + " 4 " + iron + " 7 " + crop;
  if (type == 34)
    return "4 " + wood + " 3 " + clay + " 4 " + iron + " 7 " + crop;
  if (type == 35)
    return "4 " + wood + " 4 " + clay + " 3 " + iron + " 7 " + crop;

  return "Unknown";
}

function createDetailText(x, y) {
  var city_name = details_name + ":";
  var player = "-";
  var population = "-";
  var race = "-";
  var alliance = "-";
  var idle = "-";
  var type = "-";
  var gaul_img = '<IMG SRC="/images/gaul.gif" STYLE="padding: 0px 0px 0px 0px;">';
  var roman_img = '<IMG SRC="/images/roman.gif" STYLE="padding: 0px 0px 0px 0px;">';
  var teuton_img = '<IMG SRC="/images/teuton.gif" STYLE="padding: 0px 0px 0px 0px;">';

  index = (map_size * y) + x;
  type = tile2info(map_data[index][TILE]);
  if (map_data[index] && map_data[index][VID] != 0) {
    city_name = map_data[index][VILLAGE] + " (" + map_data[index][RACE] + ")";
    player = map_data[index][PLAYER];
    if (map_data[index][TID] == 1)
      player = roman_img + " " + player;
    if (map_data[index][TID] == 2)
      player = teuton_img + " " + player;
    if (map_data[index][TID] == 3)
      player = gaul_img + " " + player;
    population = map_data[index][POP];
    alliance = map_data[index][ALLIANCE];
    idle = map_data[index][IDLE] + " days";
  }

  txt  = '<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0" WIDTH="270">';
  txt += '  <TR><TD BGCOLOR="#AAAAAA">';
  txt += '  <TABLE CELLPADDING="0" CELLSPACING="1" BORDER="0" WIDTH="270">';
  txt += '    <TR>';
  txt += '      <TD BGCOLOR="#EEEEEE" ALIGN="center" COLSPAN="2"><B>' + city_name + '</B></TD>';
  txt += '    </TR><TR>';
  txt += '      <TD BGCOLOR="#FFFFFF" WIDTH="100">&nbsp;' + player_name + ':</TD>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + player + '</TD>';
  txt += '    </TR><TR>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + population_name + ':</TD>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + population + '</TD>';
  txt += '    </TR><TR>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + alliance_name + ':</TD>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + alliance + '</TD>';
  txt += '    </TR><TR>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + idle_name + ':</TD>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + idle + '</TD>';
  txt += '    </TR><TR>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + type_name + ':</TD>';
  txt += '      <TD BGCOLOR="#FFFFFF">&nbsp;' + type + '</TD>';
  txt += '    </TR>';
  txt += '  </TABLE>';
  txt += '  </TD></TR>';
  txt += '</TABLE>';

  return txt;
}

function setCoords(x, y) {
  click_x = x; 
  click_y = y;
  txt = "<H2>" + map_name + "(" + x + " | " + y + ")</H2>";
  document.getElementById("coord_details").innerHTML = txt;
}

function showTile(x, y) {
  myHTML = createDetailText(x, y);
  document.getElementById("city_details").innerHTML = myHTML;
  coord_x = x;
  coord_y = y;

  x = x - Math.floor(map_size / 2) + current_x;
  y = (map_size - y - 1) - Math.floor(map_size / 2) + current_y;
  setCoords(x, y);
}  
