// Create a hash value to use for linked builds
function create_link( )
{
  var hash;
  var i;
  
  hash = "";
  hash += addToHash(document.getElementById("level").value, 2);
  hash += addToHash(document.getElementById("bonus").value, 4);

  for (i = 0; i < 8; i++)
  {
    hash += addToHash(document.getElementById("stat" + i).value, 2);
  } // for i
  
  for (i = 0; i < 9; i++)
  {
    hash += addToHash(document.getElementById("skill" + i).value, 2);
  } // for i

  for (i = 1; i < 11; i++)
  {
    hash += addToHash(document.getElementById("mutation" + i).value, 2);
  } // for i
  
  var fa = 9;

  for (i = 0; i < document.forms[0].faction.length; i++)
  {
    if (document.forms[0].faction[i].checked)
    {
      fa = i;
    }
  } // for i

  hash += addToHash(fa, 1);

  window.location.hash = hash;
}
// Create hex values to add to hash
function addToHash(value, len)
{
  var hD = "0123456789ABCDEF";
  var h = hD.substr(value & 15, 1);
  
  while (value > 15) 
  {
    value >>= 4;
    h = hD.substr(value & 15, 1) + h;
  } // while
  
  while (h.length < len)
  {  
    h = "0" + h;
  } // while
  
  return h;
}

function load_hash(hash)
{
  window.location.hash = hash;
  
  decode_link( );
}

// Decode the given hash link into something readable
function decode_link( )
{
  var hash = window.location.hash;

  hide_javascript_warning( );
  
  for (i = 0; i < document.forms[0].faction.length; i++)
  {
    document.forms[0].faction[i].checked = false;
  } // for i
  
  if (hash.length == 0) 
  {
    return;
  }

	var reg = /[^0-9A-F]/g;
	hash = hash.replace(reg, "");
	
  if (hash.length != 61)
  {
    alert("Invalid Build Link - Setting Defaults");
    return;
  } // else correct length of hex values

  hash = get_hash_value(hash, "level", 2);
  hash = get_hash_value(hash, "bonus", 4);

  for (i = 0; i < 8; i++)
  {
    hash = get_hash_value(hash, ("stat" + i), 2);
  } // for i
  
  for (i = 0; i < 9; i++)
  {
    hash = get_hash_value(hash, ("skill" + i), 2);
  } // for i

  for (i = 1; i < 11; i++)
  {
    hash = get_hash_value(hash, ("mutation" + i), 2);
  } // for i
  
  if (parseInt(hash) < 6)
  {
    document.forms[0].faction[hash].checked = true;
    select_faction(hash);
  }
  else
  {
    calc_ap( );
  }
}

function get_hash_value(hash, field, len)
{
  var hex, dec;
  
  hex = hash.substr(0, len);
  dec = parseInt(hex, 16);

  hash = hash.slice(len, hash.length);
    
  document.getElementById(field).value = dec;
  
  return hash;
}
