/* Aragon Online - Copyright 2003-2010 by Russell Shilling */
/* Common Javascript functions and constants */

var X_MAX = 25, Y_MAX = 25;
var TURN_INTERVAL = 7200;
var INFO_WIDTH = 300, INFO_HALF = 150;


/* *** DOM functions - cross-browser compatible *** */

/**
 *  Create a getElementById if not present
 */
if (! document.getElementById) {
  document.getElementById = function(id) {
    return document.all[id];
  }
}

/**
 *  Get the content of the node
 */
function get_content(node) {
  if (node.textContent)
    return node.textContent;
  else if (node.innerText)
    return node.innerText;
  else
    return node.text;
}

function $(e) {
  if (typeof e == 'string')
    e = document.getElementById(e);
  return e;
};


/**
 *  Set the inner HTML of an element
 */
function setHTML(strField, strValue) {
    var elm = $(strField);
    if (elm) elm.innerHTML = strValue;
}

/**
 *  Add to the inner HTML of an element
 */
function addHTML(strField, strValue) {
    var elm = $(strField);
    if (elm) elm.innerHTML = elm.innerHTML + strValue;
}

/**
 *  Set an element's title, replacing troublesome chars
 */
function setTitle(strField, strValue) {
    var elm = $(strField);
    if (elm) elm.title = strValue.replace(/&nbsp;/g, " ");
}

/**
 *  Set the title of the parent of an element
 */
function setTitleParent(strField, strValue) {
    var elm = $(strField);
    if (elm && elm.parentNode) setTitle(elm.parentNode, strValue);
}

/**
 *  Strip all the HTML out of the string
 */
function stripTags(strValue) {
  return strValue.replace(/<\/?[^>]+>/gi, '');
}

/**
 *  Resize div to fit the screen (assumes overflow is auto)
 */
function resizeToScreen(div_name) {
  var h, w;
  var div = $(div_name);
  if (is_ie) {
    w = document.documentElement.clientWidth;
    h = document.documentElement.clientHeight;
  } else {
    w = window.innerWidth  - 22;
    h = window.innerHeight - 20;
  }
  h = h - div.offsetTop;
  if (h < 400) h = 400;
  w = w - div.offsetLeft;
  if (w < 600) w = 600;
  div.style.height = h + 'px';
  div.style.width = w + 'px';
}

/**
 *  Get the value of the form 'frm' radio buttons name 'radio'
 */
function form_radio_value(frm, radio) {
  v = document.forms[frm].elements[radio];
  if (v) {
    for (var i=0; i < v.length; i++) {
      if (v[i].checked) {
        return v[i].value;
      }
    }
  }
  return 0;
}

// removes whitespace-only text node children and comment nodes
ajax_clean = function(elm) {
  var node = elm.firstChild;
  while (node) {
    var nextNode = node.nextSibling;
    if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
      elm.removeChild(node);
    else if (node.nodeType == 8)
      elm.removeChild(node);
    node = nextNode;
  }
  return elm;
};

/**
 *  Update the page with values returned by Ajax
 *  The tag is the element id, and the content is the innerHTML
 */
function ajax_update_page(x) {
  x = x.documentElement;

  // Top-level node, should be only 1
  var y = ajax_clean(x);
  // $('div_debug').innerHTML = y.length+' ';
  var v = y.firstChild;
  while (v) {
    // if (y[i].childNodes.length > 0) {
    // $('div_debug').innerHTML += v+':'+y[i].childNodes[0].nodeValue+'<br/>';
    setHTML(v.tagName, v.firstChild.nodeValue || v.nodeTypedValue);
    v = v.nextChild;
    // }
  }
};

/**
 *  Serialize one element, usually "target"
 */
ajax_serialize = function(els) {
    var els = document.getElementsByName(els);
    var len = els.length;
    var result = "";
    this.addField =
        function(value) {
            if (result.length>0) {
                result += ",";
            }
            result += value;
        };
    for (var i=0; i<len; i++) {
        var el = els[i];
        if (!el.disabled) {
            switch(el.type) {
                case 'text': case 'password': case 'hidden': case 'textarea':
                    this.addField(el.value);
                    break;
                case 'select-one':
                    if (el.selectedIndex>=0) {
                        this.addField(el.options[el.selectedIndex].value);
                    }
                    break;
                case 'select-multiple':
                    for (var j=0; j<el.options.length; j++) {
                        if (el.options[j].selected) {
                            this.addField(el.options[j].value);
                        }
                    }
                    break;
                case 'checkbox': case 'radio':
                    if (el.checked) {
                        this.addField(el.value);
                    }
                    break;
            }
        }
    }
    return encodeURIComponent(result);
};


/* *** Helper functions *** */

/**
 *  Return true if str is in arr
 *  Should work for numbers, too
 */
function in_array(str, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (str == arr[i])
      return true;
  }
  return false;
}

/**
 *  Return the index of obj in arr, -1 if not found
 */
function search_array(obj, arr) {
  for (var i = 0; i < arr.length; i++) {
    if (str == arr[i])
      return i;
  }
  return -1;
}

/**
 *  Just like PHP number_format
 */
function number_format(value, decimal) {

  var d = decimal || 0;
  var v = Math.abs(value).toFixed(d).toString().split('.');

  // Whole part
  var w = new Array();
  for (var i = v[0].length - 1, j = 1; i >= 0; --i, ++j) {
    w.unshift(v[0][i]);
    if (i > 0 && j % 3 == 0) w.unshift(',');
  }
  // Decimal, if any
  var x = d ? '.' + v[1] : '';

  // Sign + Whole + Fraction
  return (value < 0 ? '-' : '') + w.join('') + x;
}

/**
 *  Log out verify function
 */
function log_out()
{
    ht = document.getElementsByTagName("html");
    ht[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
    if (confirm('Are you sure you want to Log Out?'))
    {
        return true;
    }
    else
    {
        ht[0].style.filter = "";
        return false;
    }
}

/**
 *  Generate an approximate number of lines that the text (strtocount)
 *  will occupy in a text box with the given number of columns (col)
 */
function textbox_count_lines(strtocount, cols) {
    var hard_lines = 1;
    var last = 0;
    while ( true ) {
        last = strtocount.indexOf("\n", last+1);
        hard_lines ++;
        if ( last == -1 ) break;
    }
    var soft_lines = Math.round(strtocount.length / (cols-1));
    return hard_lines + soft_lines;
}
/**
 *  Auto-resize text boxes to fit the contents
 */
function textbox_resize(n) {
  var all_forms = document.forms;
  for ( var the_form in all_forms ) {
    for ( var x in the_form ) {
      if ( ! the_form[x] ) continue;
      if ( typeof the_form[x].rows != "number" ) continue;
      if ( the_form[x].name != n ) continue;

      var r = textbox_count_lines(the_form[x].value,the_form[x].cols) + 1;
      if (r > 3)
        the_form[x].rows = r;
      else
        the_form[x].rows = 3;
    }
  }
  // setTimeout("textbox_resize();", 500);
}

/**
 *  Find the position of an element in absolute coordinates
 */
function find_pos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    if (obj.offsetParent)
      do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
  }
  return [curleft, curtop];
}

/**
 *  Scroll the Parent div/window so an object is visible
 */
function make_visible(objParent, objName) {
  var curleft = curtop = 0;
  var pnt = $(objParent);
  var obj = $(objName);
  if (pnt && obj) {
    if (obj.offsetParent) {
      curleft = obj.offsetLeft
      curtop = obj.offsetTop
      while (obj = obj.offsetParent) {
        if (obj == pnt) break;
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
      }
    }
    pnt.scrollLeft = curleft;
    pnt.scrollTop = curtop;
  }
}

/**
 *  Warn the user if there are unsaved changes.
 *  changed is set to 1 on an edit, confirm_enabled set to
 *  0 to disable this message, usually on a form submit.
 */
var changed = 0;
var confirm_enabled = 1;

function confirm_exit(event) {
  if (changed) {
    var UNLOAD_MSG = "You are about to leave this page.  " +
        "Any changes made will be lost if you don't " +
        "Save. Are you sure you want to exit this page?";
    if (confirm_enabled)
      if(window.event)
        window.event.returnValue = UNLOAD_MSG; // IE
      else
        return UNLOAD_MSG; // FX
    else
      confirm_enabled = 1;
  }
}

/**
 *  Alert the player if there is a script or lore message
 *  Substitute [] to <> for HTML tags, special handling for
 *  Illuminated text [x], Indent [_] and convert new lines
 *  to break.
 */
function message_alert(title, txt) {
  var a = $('message_window');
  var b = $('message_title');
  var c = $('message_txt');
  if (a && b && c) {
    b.innerHTML = "<b>"+title+"</b>";
    var i;
    c.innerHTML = txt;
    a.style.display = 'block';
  }
  var d = $('message_restore');
  if (d)
    d.style.display = 'none';
}

/**
 *  Show the message div and hide the restore div
 */
function message_open() {
  var a = $('message_window');
  if (a)
    a.style.display = 'block';
  var d = $('message_restore');
  if (d)
    d.style.display = 'none';
}

/**
 *  Hide the message div and show the restore div
 */
function message_close() {
  var a = $('message_window');
  if (a)
    a.style.display = 'none';
  var d = $('message_restore');
  if (d)
    d.style.display = 'block';
}

/**
 *  Utility function to check/uncheck all checkboxes
 *  in the form (me)
 */
function check_all(me) {
  me = $(me);
  var frm = me.form;
  for (var i = 0; i < frm.elements.length; i++) {
    var e = frm.elements[i];
    if ( (e.name != me.name) && (e.type=='checkbox') && (!e.disabled) ) {
      e.checked = me.checked;
    }
  }
}

// Update the global control array
// Probably want to actually do something with these results!
update_control = function(items) {

  var context = 0, refresh = 0;

  if (items) {
    if (items.getElementsByTagName('context').length) {
      var nodes = items.getElementsByTagName('context')[0];
      context = get_content(nodes);
    }
    if (items.getElementsByTagName('result').length) {
      var nodes = items.getElementsByTagName('result')[0];
      var result = get_content(nodes);
      var x = $('control_result');
      x.innerHTML = result;
    }
    // Map Size
    if (items.getElementsByTagName('field6').length) {
      var nodes = items.getElementsByTagName('field6')[0];
      var field6 = get_content(nodes);
      refresh = 1;
    }
    // Unit Display
    if (items.getElementsByTagName('field7').length) {
      var nodes = items.getElementsByTagName('field7')[0];
      var field7 = get_content(nodes);
      refresh = 1;
    }
    // Sound Volume
    if (items.getElementsByTagName('field8').length) {
      var nodes = items.getElementsByTagName('field8')[0];
      var field8 = get_content(nodes);
      var v = ['Off','Low','Medium','High','Full'].indexOf(field8);
      if (v >= 0)
        control_volume = v * 25;
    }
    // Animations
    if (items.getElementsByTagName('field9').length) {
      var nodes = items.getElementsByTagName('field9')[0];
      var field9 = get_content(nodes);
    }
    // Results
    if (items.getElementsByTagName('field10').length) {
      var nodes = items.getElementsByTagName('field10')[0];
      var field10 = get_content(nodes);
    }
    // AI Strategy
    if (items.getElementsByTagName('field11').length) {
      var nodes = items.getElementsByTagName('field11')[0];
      var field11 = get_content(nodes);
    }
    // AI Militia
    if (items.getElementsByTagName('field12').length) {
      var nodes = items.getElementsByTagName('field12')[0];
      var field12 = get_content(nodes);
    }
    if (context == 10) {
      if (refresh) {
        window.location.reload();
        return;
      }
    }
  }
}

// Dont allow calls to pile up
var npc_turn_flag = 0;

// NPC Turn periodic call using ajax
function npc_turn() {

  if (! npc_turn_flag) {
    npc_turn_flag = 1;

    AjaxRequest.get(
      {
        'url':'npcturn.php',
        'onSuccess': function(req) { npc_next(req.responseXML); }
      }
    );
  }
}

function npc_next(items) {
  npc_turn_flag = 0;

  if (items && scale !== undefined && scale == 3) {
    var player_julian, max_julian, next_turn;
    if (items.getElementsByTagName('player_julian').length) {
      var nodes = items.getElementsByTagName('player_julian')[0];
      player_julian = parseInt(get_content(nodes));
    }
    if (items.getElementsByTagName('max_julian').length) {
      var nodes = items.getElementsByTagName('max_julian')[0];
      max_julian = parseInt(get_content(nodes));
    }
    if (items.getElementsByTagName('next_turn').length) {
      var nodes = items.getElementsByTagName('next_turn')[0];
      next_turn = parseInt(get_content(nodes));
      if (player_julian < max_julian) {
        content = "<a href='gameturn.php?"+SESSIONURL+
                "' onclick='return confirm(\"Next World Turn:  Are you sure?\");'>" +
                "<img border='0' width='80' height='18' src='/grafix/btn_next_turn.png' alt='Next Turn'></a>"  +
                    "&nbsp;<input type='checkbox' id='all' name='all' checked>ALL" +
                    "<input type='hidden' id='unit_list' value=''>";
      } else if (next_turn) {
        content = 'Next turn in '+(TURN_INTERVAL / 60 - Math.floor(next_turn / 60))+' minutes.';
      }
      setHTML('game_turn', content);
    }
  }
}


