/* Aragon Online - Copyright 2003-2011 by Russell Shilling */
/* map.js */


init_map = function() {

  // Thumb doesnt need anything
  if (scale > 3) {
    on_resize(0);
    return;
  }

  var folders = ['dungeon','tactical','region','world'];

  var div_map = $('div_map');

  var terr;
  var feat = null;

  for (var x = 0; x < X_MAX; x++)
    for (var y = 0; y < Y_MAX; y++) {

      var y_adj = X_SCALE - Y_SCALE;

      var elm = document.createElement('map');
      elm.setAttribute('id', 'm_'+x+'_'+y);
      elm.setAttribute('name', 'm_'+x+'_'+y);

      // Build the AREA tags and set with innerHTML because of IE quirk/bug
      var s = "<area href='javascript:do_click("+x+","+y+")' onmouseover='on_mouseover("+x+","+y+");' onmouseout='on_mouseout();' "
        +"shape='rect' coords='1,"+y_adj+","+(X_SCALE-1)+","+Y_SCALE+"'>";
      if (y > 0)
        s += "<area href='javascript:do_click("+x+","+(y-1)+")' onmouseover='on_mouseover("+x+","+(y-1)+");' onmouseout='on_mouseout();' "
          +"shape='rect' coords='1,0,"+(X_SCALE-1)+","+(y_adj-1)+"'>";
      elm.innerHTML = s

      div_map.appendChild(elm);

      var terr = document.createElement('img');
      if (scale == 0)
        terr.src = 'dng.php?s='+size+'&t=' + map[x][y][0] + '&f=' + tile_file;
      else
        terr.src = 'tile.php?s='+size+'&x='+(x & 3)+'&y='+(y & 3)+
            '&f='+season_folder+'&w='+weather_tile+'&t=' + map[x][y][0];

      // terr.src = './tile/' + map[x][y][0] + '.png';
      terr.id = 't_'+x+'_'+y;
      terr.style.border = 0;
      terr.style.position = 'absolute';
      terr.style.left = (x * X_SCALE) + 'px';
      terr.style.top = (terrain_scrn_y(x,y)) + 'px';
      terr.style.zIndex = y * 20;
      terr.setAttribute('useMap', '#m_'+x+'_'+y);

      div_map.appendChild(terr);

      var scrn_y = feature_scrn_y(x,y);

      // effect0 under the feature
      var effect0 = map[x][y][2];
      var eff0 = null;

      eff0 = document.createElement('img');
      eff0.id = 'e0_'+x+'_'+y;
      if (effect0.length) {
        eff0.src = './grafix/' + folders[scale] + '/' + effect0;
      } else {
        eff0.src = './grafix/0.png';
      }
      eff0.style.border = 0;
      eff0.style.position = 'absolute';
      eff0.style.left = (x * X_SCALE) + 'px';
      eff0.style.top = scrn_y + 'px';
      eff0.style.zIndex = y * 20 + 1;
      if (effect0.length) {
        eff0.width = X_SCALE;
        eff0.height = X_SCALE;
      }
      eff0.setAttribute('useMap', '#m_'+x+'_'+y);

      div_map.appendChild(eff0);

      var feature = map[x][y][1];
      var feat;

      feat = document.createElement('img');
      feat.id = 'f_'+x+'_'+y;
      var y_top = scrn_y - Math.floor(X_SCALE / 16);
      if (scale == 0) {
        if (feature.length == 0) {
          feat.src = './grafix/0.png';
        } else {
          feat.src = './grafix/' + folders[scale] + '/' + feature + '.png';
        }
      } else {
        if (feature.length == 0) {
          feat.src = './grafix/0.png';
        } else if (in_array(feature.substr(0,3), ['lnd','agr','swp','for','hil','mtn','top'])) {
          feat.src = './grafix/' + season_folder + '/' + feature + '.png';
        } else if (in_array(feature.substr(0,3), ['tmb','mtl','min','rck','lod','ore','tmb','qur','b1','b2','r1','r2'])) {
          feat.src = './grafix/' + feature + '.png';
        } else if (in_array(feature.substr(0,3), ['cav','twr','vlc','rui'])) {
          feat.src = './grafix/' + folders[scale] + '/' + feature + '.gif';
        } else {
          feat.src = './grafix/' + folders[scale] + '/' + map_race_abr + '/' + feature + '.png';
        }
      }
      feat.style.border = 0;
      feat.style.position = 'absolute';
      feat.style.left = (x * X_SCALE) + 'px';
      feat.style.top = y_top + 'px';
      feat.style.zIndex = y * 20 + 2;
//      if (feature.length) {
        feat.width = X_SCALE;
        feat.height = X_SCALE;
//      }
      feat.setAttribute('useMap', '#m_'+x+'_'+y);

      div_map.appendChild(feat);

      // effect1 over the feature
      var effect1 = map[x][y][3];
      var eff1;

      eff1 = document.createElement('img');
      eff1.id = 'e1_'+x+'_'+y;
      if (effect1.length) {
        eff1.src = './grafix/' + folders[scale] + '/' + effect1;
      } else {
        eff1.src = './grafix/0.png';
      }
      eff1.style.border = 0;
      eff1.style.position = 'absolute';
      eff1.style.left = (x * X_SCALE) + 'px';
      eff1.style.top = scrn_y + 'px';
      eff1.style.zIndex = y * 20 + 3;
      if (effect1.length) {
        eff1.width = X_SCALE;
        eff1.height = X_SCALE;
      }
      eff1.setAttribute('useMap', '#m_'+x+'_'+y);

      div_map.appendChild(eff1);
    }

  on_resize(1);
}

function on_mouseover(x,y) {

  if ($('x') == null)
    return;

  var xx = x, yy = y;
  if (scale == 3) {
    xx += origin_x;
    yy += origin_y;
  }
  setHTML('cursor_coord', '('+xx+', '+yy+')');
  var descr, effect;
  if (scale == 0) {
    descr = '&nbsp;';
  } else {
    var f, v, feature = map[x][y][1];
    var effect0 = map[x][y][2], effect1 = map[x][y][3];
    if (parseInt(feature.substr(1,1)) > 0) {
      f = feature.substr(0,1);
      v = feature.substr(1,1);
    } else {
      f = feature.substr(0,3);
      v = feature.substr(3,1);
    }
    descr = terr_descr[map[x][y][0].substr(0,1)] + (feature ? ', ' + feat_descr[f] + ' ' + v: '');
    elev = 'Elev: ' + map[x][y][5] + ', Hgt: '+map[x][y][4];
    effect = (effect0.length ? capitalize(effect0.replace(/\.gif/,'')) : '')
      + (effect0.length >0 && effect1.length > 0 ? ', ' : '')
      + (effect1.length ? capitalize(effect1.replace(/\.gif/,'')) : '');
    if (effect.length == 0) effect = '&nbsp;';
    if (scale <= 1 && $('cursor_other')) {
      var xs = parseInt($('x').innerHTML, 10);
      var ys = parseInt($('y').innerHTML, 10);
      other = 'Rng: ' + distance(xs,ys, x,y) + ', LOS: ' + (line_of_sight (xs,ys, x,y) ? 'Yes' : 'No');
    } else {
      other = '&nbsp;';
    }
  }
  setHTML('cursor_terr', descr);
  setHTML('cursor_elev', elev);
  setHTML('cursor_effect', effect);
  setHTML('cursor_other', other);
}
function capitalize(s) { return s.substring(0,1).toUpperCase() + s.substring(1); }

function on_mouseout() {
  setHTML('cursor_coord', '');
  setHTML('cursor_terr', '&nbsp;');
  setHTML('cursor_elev', '&nbsp;');
  setHTML('cursor_effect', '&nbsp;');
  setHTML('cursor_other', '&nbsp;');
  hide_blocked(1);
  // hide_blocked(2);
}

// Fit the unit menu and map, center map on units (if any)
function on_resize(center) {

  var h, w;
  var div_map = $('div_map');
  var div_info = $('div_info');

  // Get the width of the browser window
  if (document.documentElement && document.documentElement.clientWidth) {
    w = document.documentElement.clientWidth;
    h = document.documentElement.clientHeight;
  } else {
    w = window.innerWidth  - 22;
    h = window.innerHeight - 20;
  }
  h = h - div_map.offsetTop;
  if (h < 400) h = 400;
  w = w - div_map.offsetLeft;
  if (w < 600) w = 600;
  div_map.style.height = h + 'px';
  div_map.style.width = w + 'px';

  if (center && scale <= 3) {
    w = parseInt(div_map.offsetWidth);
    h = parseInt(div_map.offsetHeight);

    // Find the center of units, if any
    var minx = MAP_WIDTH, miny = MAP_HGT, maxx = 0, maxy = 0;

    var div_units = $('div_units');
    if (div_units) {

      var uu = div_units.getElementsByTagName('img');
      for (var i in uu) {
        var u = uu[i];
        if (u && u.id && u.id.substr(0,8) == 'imgunit_') {
          if (u.offsetLeft < minx) minx = u.offsetLeft;
          if (u.offsetTop < miny) miny = u.offsetTop;
          if (u.offsetLeft+u.offsetWidth > maxx) maxx = u.offsetLeft+u.offsetWidth;
          if (u.offsetTop+u.offsetHeight > maxy) maxy = u.offsetTop+u.offsetHeight;
        }
      }
    }

    // Center the map on the center of the units
    div_map.scrollLeft = Math.max(0, Math.min((MAP_WIDTH - w), (minx + maxx - w) / 2));
    div_map.scrollTop = Math.max(0, Math.min((MAP_HGT - h), (miny + maxy - h) / 2));
  }
}

// UNIT MOVEMENT SUPPORT FUNCTIONS
var unit_path = new Array();

main_init_page = function() {
  AjaxRequest.post(
    {
      'url': 'unitaction.php',
      'parameters': { 'action': 'init', 's': vb_session_hash },
      'onSuccess': function(req) { main_update_page(req.responseXML); },
      'onError': function(req) {
        var title = "Error main_init_page: " + req.statusText;
        var txt = req.responseText;
        message_alert(title, txt);
      }
    }
  );
//  var post = 'action=init';
//  ajax.post('unitaction.php?'+SESSIONURL,main_update_page,post);

  npc_turn_flag = 0;
}


main_show_message = function(message) {

  var msg = $('status_message');
  if (msg) {
    msg.innerHTML = '<img src="/grafix/rotating_arrow.gif">&nbsp;' + message;
    msg.style.display = 'inline';
    msg.style.visibility = 'visible';
  }
}

main_update_units = function(items) {

  // Retry if there was an error
  if (items == null) {
    ++error_retries;
    if (error_retries <= 3) {
      AjaxRequest.post(
        {
          'url': 'unitaction.php',
          'parameters': { 'action': 'npc', 's': vb_session_hash },
          'onSuccess': function(req) { main_update_units(req.responseXML); },
          'onError': function(req) { main_update_units(req.responseXML); }
        }
      );
    } else {
      AjaxRequest.post(
        {
          'url': 'unitaction.php',
          'parameters': { 'action': 'npc', 's': vb_session_hash },
          'onSuccess': function(req) { main_update_units(req.responseXML); },
          'onError': function(req) {
            var title = "Error main_update_units.retry: " + req.statusText;
            var txt = req.responseText;
            message_alert(title, txt);
          }
        }
      );
    }
    return;
  }

  // Apply map effects
  if (items.getElementsByTagName('map_effects').length) {
    var nodes = items.getElementsByTagName('map_effects')[0];
    var map_effects = get_content(nodes);
    if (map_effects.length) {
      eval(map_effects);
    }
  }

  // Animations
  if (items.getElementsByTagName('anim').length) {
    var nodes = items.getElementsByTagName('anim')[0];
    var value = get_content(nodes);
    if (value.length) {
      animation_stack = value.split(";");
      // begin_animations();
    }
  }

  // If there is a change in scale, or an encounter,
  // force a refresh so the scale will change!
  if (items.getElementsByTagName('refresh').length) {
    var nodes = items.getElementsByTagName('refresh');
    if (nodes.length) {
      var refresh = parseInt(get_content(nodes[0]));
      if (refresh) {
        var nodes = items.getElementsByTagName('battle');
        var battle = parseInt(get_content(nodes[0]));
        if (scale == 2 && battle > 0) {
          if (battle == 3)
            main_show_message('<b>Your city is under attack!</b>');
          else if (battle == 2)
            main_show_message('<b>You have entered a hostile city!</b>');
          else
            main_show_message('<b>You have encountered hostile forces!</b>');
          window.location.href = window.location.href;
          return;
        } else {
          window.location.href = window.location.href;
          return;
        }
      }
    }
  }

  // Update units
  if (items.getElementsByTagName('div_units').length) {
    var nodes = items.getElementsByTagName('div_units')[0];
    div_units = get_content(nodes);
    // Delay updating until animations have completed
    // setHTML('div_units', div_units);
    // main_init_page();
  }

  // Message
  if (items.getElementsByTagName('message').length) {
    var nodes = items.getElementsByTagName('title');
    var title = get_content(nodes[0]);
    var nodes = items.getElementsByTagName('message');
    var message = get_content(nodes[0]);
    if (message.length) {
      message_alert(title, message);
    }
  }

  // Check if turn changed, and do another npc turn if not
  if (items.getElementsByTagName('turn').length) {
    var nodes = items.getElementsByTagName('player');
    var player = parseInt(get_content(nodes[0]));
    nodes = items.getElementsByTagName('enemy');
    var enemy = parseInt(get_content(nodes[0]));
    if (player > 0 && enemy > 0) {
    
      nodes = items.getElementsByTagName('player_clock');
      var player_clock = parseInt(get_content(nodes[0]));
      nodes = items.getElementsByTagName('enemy_clock');
      var enemy_clock = parseInt(get_content(nodes[0]));

      ++turn_retries;
      if ((turn_retries < 3) && (player_clock > enemy_clock)) {
        main_show_message('<b>Please Wait...</b>');
        AjaxRequest.post(
          {
            'url': 'unitaction.php',
            'parameters': { 'action': 'npc', 's': vb_session_hash },
            'onSuccess': function(req) { main_update_units(req.responseXML); },
            'onError': function(req) {
              var title = "Error main_update_units.turn: " + req.statusText;
              var txt = req.responseText;
              message_alert(title, txt);
            }
          }
        );
        // ajax.post('unitaction.php?'+SESSIONURL,main_update_units,'action=npc');
      }
    }
  }

  // Always call this
  begin_animations();

  // reset error retries counter
  error_retries = 0;
}

// Work-around Firefox breaking nodes into 4096 byte chunks
get_content = function(node) {
  var content = '';
  try {
    for (var k = 0; k < node.childNodes.length; k++) {
      // eliminate text and comment nodes in NN and FF
      if (node.nodeType != 3 && node.nodeType != 8) {
        content += node.childNodes[k].nodeValue;
      }
    }
  } catch (e) {
  }
  return content;
}

var drag_info;

main_update_page = function(items) {
  if (items) {
    // debugger;
    
    // Refresh
    if (items.getElementsByTagName('refresh').length) {
      var nodes = items.getElementsByTagName('refresh');
      if (nodes.length) {
        var refresh = parseInt(get_content(nodes[0]));
        if (refresh) {
          window.location.href = window.location.href;
          return;
        }
      }
    }

    // Message
    if (items.getElementsByTagName('message').length) {
      var nodes = items.getElementsByTagName('title');
      var title = get_content(nodes[0]);
      var nodes = items.getElementsByTagName('message');
      var message = get_content(nodes[0]);
      if (message.length) {
        message_alert(title, message);
      }
    }

    // Floating menu
    if (items.getElementsByTagName('info_bar').length) {
      var nodes = items.getElementsByTagName('info_bar')[0];
      var content = get_content(nodes);
      setHTML('div_info', content);

      if (typeof drag_info == "undefined") {
        drag_info = new dragObject("div_info", "div_info_handle");
      }
    }

    // Equip update
    if (items.getElementsByTagName('equip').length) {
      var unit_id, equip_id;
      var nodes = items.getElementsByTagName('equip');
      for (i = 0; i < nodes.length; i++) {
        var node = nodes[i].childNodes;
        for (j = 0; j < node.length; j++) {
          // eliminate text and comment nodes in NN and FF
          if (node[j].nodeType != 3 && node[j].nodeType != 8) {
            if (node[j].childNodes.length > 0) {
              var value = get_content(node[j]);
              if (value == null) value = '';
              // $('div_debug').innerHTML += node[j].tagName+':'+value+'<br/>';
              var tag = node[j].tagName;
              if (tag == 'unit_id') {
                unit_id = parseInt(value);
              } else if (tag == 'equip_id') {
                equip_id = parseInt(value);
              } else if (tag == 'equipped') {
                var e = $('equip['+unit_id+']['+equip_id+']');
                if (e) e.checked = (value == '1');
              }
            }
          }
        }
      }
    }

    if (items.getElementsByTagName('unit').length) {
      erase_path();
      if (scale < 3) {
        var unit_id, src_x, src_y, path, dst_x, dst_y, cursor_x, cursor_y;
        var nodes = items.getElementsByTagName('unit');
        for (i = 0; i < nodes.length; i++) {
          var node = nodes[i].childNodes;
          var action_menu = '', spell_menu = '', cast_menu = '';
          for (j = 0; j < node.length; j++) {
            // eliminate text and comment nodes in NN and FF
            if (node[j].nodeType != 3 && node[j].nodeType != 8) {
              if (node[j].childNodes.length > 0) {
                var value = get_content(node[j]);
                if (value == null) value = '';
                // $('div_debug').innerHTML += node[j].tagName+':'+value+'<br/>';
                var tag = node[j].tagName;
                if (tag == 'unit_id') {
                  unit_id = parseInt(value);
                } else if (tag == 'ai') {
                  setHTML('unit_ai['+unit_id+']', value);
                } else if (tag == 'action') {
                  action_menu = value;
                } else if (tag == 'spell') {
                  spell_menu = value;
                } else if (tag == 'cast') {
                  cast_menu = value;
                } else if (tag == 'x') {
                  src_x = parseInt(value);
                } else if (tag == 'y') {
                  src_y = parseInt(value);
                } else if (tag == 'cursor_x') {
                  cursor_x = parseInt(value);
                } else if (tag == 'cursor_y') {
                  cursor_y = parseInt(value);
                } else if (tag == 'cost') {
                  cost = parseInt(value);
                  if ($('cost['+unit_id+']'))
                    $('cost['+unit_id+']').value = cost;
                } else if (tag == 'curr_action') {
                  setHTML('curr_action['+unit_id+']', value);
                } else if (tag == 'curr_hint') {
                  setTitle('curr_action['+unit_id+']', value);
                } else if (tag == 'path') {
                  path = value;
                  if ($('path['+unit_id+']'))
                    $('path['+unit_id+']').value = path;
                }
              }
            }
          }
          if (action_menu.length) setHTML('unit_action['+unit_id+']', action_menu);
          if (spell_menu.length) setHTML('unit_spell['+unit_id+']', spell_menu);
          if (cast_menu.length) setHTML('unit_cast['+unit_id+']', cast_menu);

          var x = -1;
          var y;
          if (scale == 3) {
            x = cursor_x - origin_x;
            y = cursor_y - origin_y;
          } else {
            x = cursor_x;
            y = cursor_y;
          }
          // if (x >= 0) do_click(x, y);
        }
      }
    }
  }

  // main_show_turn();
  on_resize(0);

  update_top_menu();

  npc_turn_flag = 0;

  // Init scheduled task
  npc_next();
}

var plan_visible = false;

// Show or Hide the Unit Plan
function toggle_plan() {
  var plan = $('div_plan');
  // var label = $('toggle_plan');
  if (plan) {
    if (plan_visible) {
      plan.style.visibility = 'hidden';
      plan.innerHTML = "";
      // label.innerHTML = "<img src='/grafix/btn_plus_plan.png' alt='Show Unit Plan'>";
    } else {
      plan.style.visibility = 'visible';
      plan.innerHTML = "<img src='unitplan.php?cachebust=" + new Date().getTime() + "'>";
      // label.innerHTML = "<img src='/grafix/btn_minus_plan.png' alt='Hide Unit Plan'>";
    }
    plan_visible = ! plan_visible;
  }
}

// Highlight a hex
function hex_hilite(xx,yy) {
  img = $('t_'+xx+'_'+yy);
  if (img) {
    if (is_ie) 
      img.style.filter = 'alpha(opacity=30)';
    else 
      img.style.opacity = '0.3';
  }
}

// Show path
function show_path(x, y, path) {
  for (k = 0; k < path.length; k++) {
    var d = parseInt(path.substr(k,1));
    y = move_y(x,y,d);
    x = move_x(x,y,d);
    if (scale >= 3) {
      xx = x - origin_x;
      yy = y - origin_y;
    } else {
      xx = x;
      yy = y;
    }
    if (in_map(xx,yy)) {
      unit_path.unshift([xx,yy]);
      img = $('t_'+xx+'_'+yy);
      if (img) {
        if (is_ie) 
          img.style.filter = 'alpha(opacity=70)';
        else 
          img.style.opacity = '0.7';
      }
    }
  }
}

// Erase the path
function erase_path() {
  for (j = 0; j < unit_path.length; j++) {
    c = unit_path[j];
    xx = c[0];
    yy = c[1];
    img = $('t_'+xx+'_'+yy);
    if (img) {
      if (is_ie) 
        img.style.filter = '';
      else 
        img.style.opacity = '';
    }
  }
  unit_path = [];
}


// Highlight the out-of-bounds portion of the map
function newgame_hilite() {
  var xx, yy;
  // Top and bottom
  for (xx = 0; xx < X_MAX; ++xx) {
    for (yy = 0; yy < 5; ++yy)
      hex_hilite(xx,yy);
    for (yy = 20; yy < Y_MAX; ++yy)
      hex_hilite(xx,yy);
  }
  // Left and right
  for (yy = 5; yy < Y_MAX-5; ++yy) {
    for (xx = 0; xx < 5; ++xx)
      hex_hilite(xx,yy);
    for (xx = X_MAX-5; xx < X_MAX; ++xx)
      hex_hilite(xx,yy);
  }
}

// Place the cursor on the map at x,y
function place_cursor(x,y) {

  if (x >= 0) {
    var scrn_y = feature_scrn_y(x,y) + Y_HALF/4;
    var scrn_x = x * X_SCALE;

    var cursor = $('cursor');

    cursor.style.left = '' + scrn_x + 'px';
    cursor.style.top = '' + scrn_y + 'px';

    var map_cursor = $('map_cursor');
    map_cursor.areas[0].setAttribute('href', "javascript:do_click(" + x + "," + y + ")");
    map_cursor.areas[0].setAttribute('onmouseover', "javascript:on_mouseover(" + x + "," + y + ")");
    map_cursor.areas[0].setAttribute('onmouseout', "javascript:on_mouseout()");
    var units = $('unit_'+x+'_'+y);
    if (units)
      map_cursor.title = units.title;
    else
      map_cursor.title = null;
  }
}

// Place the crosshair on the map at x,y
function place_crosshair(x,y) {

  if (x >= 0) {
    var scrn_y = feature_scrn_y(x,y) + Y_HALF/4;
    var scrn_x = x * X_SCALE;

    var crosshair = $('crosshair');

    crosshair.style.left = '' + scrn_x + 'px';
    crosshair.style.top = '' + scrn_y + 'px';
    crosshair.style.display = 'inline';

    var map_crosshair = $('map_crosshair');
    map_crosshair.areas[0].setAttribute('href', "javascript:do_click(" + x + "," + y + ")");
    map_crosshair.areas[0].setAttribute('onmouseover', "javascript:on_mouseover(" + x + "," + y + ")");
    map_crosshair.areas[0].setAttribute('onmouseout', "javascript:on_mouseout()");
    var units = $('unit_'+x+'_'+y);
    if (units)
      map_crosshair.title = units.title;
    else
      map_crosshair.title = null;
  }
}

