var mousePosX;
var mousePosY;
var lastLayer = "";
var lastSubmitTime = -1;
var currentTickSafeAgentCallArgs = null;

function addNumberSepartors(number)
{
	var numberString = new String(number);
	var rgx = /(\d+)(\d{3})/;
	while(rgx.test(numberString))
  {
		numberString = numberString.replace(rgx, '$1' + '\'' + '$2');
	}
	return numberString;
}

function dataFlood()
{
  var date = new Date();
  submitTime = date.getMinutes()*60+date.getSeconds()+date.getMilliseconds()/1000;
  if(Math.abs(submitTime - lastSubmitTime) >= 0.4)
  {
    lastSubmitTime = submitTime;
    return false;
  }
  else
  {
    return true;
  }
}

function safeAgentCall()
{
  if(!dataFlood())
  {
    agent.call.apply('', safeAgentCall.arguments);
  }
  else
  {
    var floodMsg = new Array();
    floodMsg[0] = "Take it easy ;-)";
    floodMsg[1] = "You have quit a quick finger ;-)";
    floodMsg[2] = "Don't let the cat play with your keyboard ;-)";
    floodMsg[3] = "Get your nose of the enter key ;-)";
    floodMsg[4] = "Just once per second ;-)";
    var msgNumber = parseInt(Math.random()*4);
    
    /*lastSubmitTime = -1;
    loadLayerData('get_error_window', 'error', false, floodMsg[msgNumber]);
    var date = new Date();
    lastSubmitTime = date.getMinutes()*60+date.getSeconds()+date.getMilliseconds()/1000;*/
    alert(floodMsg[msgNumber]);
  }
}

function tickSafeAgentCall()
{
  currentTickSafeAgentCallArgs = tickSafeAgentCall.arguments;
   agent.call('', 'check_call_safety', 'callSafetyChecked');
}

function callSafetyChecked(isCallSafe)
{
  if(isCallSafe == false)
  {
    alert("Sorry, function not available during tick calculation!");
  }
  else
  {
    safeAgentCall.apply('', currentTickSafeAgentCallArgs);
  }
}

/*function menuButtonClick(buttonName, imgName, fieldName)
{
  safeAgentCall('', 'menu_button_click', 'menuButtonClicked', buttonName, imgName, fieldName);
}*/

function menuButtonClicked(status)
{
  alert(status['button_name']+" "+status['img_name']);
  if(status != null)
    document.getElementById(status['button_name']).src = status['img_name']+"_inactive.gif";
}

function changeBoxState(boxTitle)
{
  var boxState = document.getElementById("box_state_"+boxTitle).value;
  var boxTable = document.getElementById("box_"+boxTitle);
  if(boxState == "maximized")
  {
    for(var i=1; i<boxTable.rows.length-1; i++)
    {
      boxTable.rows[i].style.display = "none";
    }
    /*document.getElementById("box_content_"  +boxTitle).style.display = "none";*/
    document.getElementById("box_state_"    +boxTitle).value         = "minimized";
    document.getElementById("box_state_img_"+boxTitle).src           = "game/gfx/ui/box_state_minimized.gif";
  }
  else if(boxState == "minimized")
  {
    for(var i=1; i<boxTable.rows.length-1; i++)
    {
      boxTable.rows[i].style.display = "";
    }
    /*document.getElementById("box_content_"  +boxTitle).style.display = "";*/
    document.getElementById("box_state_"    +boxTitle).value         = "maximized";
    document.getElementById("box_state_img_"+boxTitle).src           = "game/gfx/ui/box_state_maximized.gif";
  }
}

function enterKeyPressed(e)
{
  if(!e)
  {
    e = window.event;
    code = e.which;
  }
  else
  {
    code = e.keyCode;
  }
  if(code == 13)
  {
    return true;
  }
  else
  {
    return false;
  }
}

function loadLayerDataTextBox(event, layerFunction, layerName, autoClose, textBoxId)
{
  if(enterKeyPressed(event))
  {
    var query = document.getElementById(textBoxId).value;
    lastLayer = layerName;
    safeAgentCall('', layerFunction, 'showLayerData', layerName, query, textBoxId);
  }
}

function loadLayerData(layerFunction, layerName, autoClose, layerFunctionParameter)
{
  lastLayer = layerName;
  safeAgentCall('', layerFunction, 'showLayerData', layerName, layerFunctionParameter);
}

function showLayerData(data)
{
  data['content'] = unescape(data['content']);
  showLayer(data['layer_name'], data['content']);
  
  if(data['callback_parameter'] != null)
    var callbackParameter = data['callback_parameter'];
  if(data['callback_function'] != null)
    this[data['callback_function']](callbackParameter);
}

function showLayer(layerName, content)
{
	var layerNameString = new String(layerName);
	document.getElementById(layerName).innerHTML      = content;
  document.getElementById(layerName).style.display  = "";
	document.getElementById(layerName).style.position = "absolute";
  document.getElementById(layerName).style.zIndex   = layerNameString.substr(layerNameString.length-1, 1);
  document.getElementById(layerName).style.left     = mousePosX;
  document.getElementById(layerName).style.top      = mousePosY;
}

function closeLayer(layerName)
{
  document.getElementById(layerName).style.display = "none";
}

function storeValueAndCloseLayer(layerName, textBoxId, value)
{
  document.getElementById(layerName).style.display = "none";
  document.getElementById(textBoxId).value = value;
}

function findUser(e)
{
  if(enterKeyPressed(e))
  {
    var query = document.getElementById("user_query_field").value;
    safeAgentCall('', 'find_user', 'showUserList', query);
  }
}

function showUserList(data)
{
  var table = document.getElementById('user_query_table');
  
  for(var i=table.rows.length-1; i>=0; i--)
  {
    table.deleteRow(i);
  }
  
  if(data.length == 0)
  {
    table.insertRow(0);

    table.rows[0].insertCell(0);
    table.rows[0].cells[0].colSpan = 3;
    table.rows[0].cells[0].className = "txt_medium_error";
    table.rows[0].cells[0].innerHTML = "No results!";
  }

  for(var i=0; i<data.length; i++)
  {
    table.insertRow(i);

    table.rows[i].insertCell(0);
    table.rows[i].cells[0].className = "txt_medium_normal";
    table.rows[i].cells[0].innerHTML = data[i]['coord_a']+":"+data[i]['coord_b']+":"+data[i]['coord_c'];
    
    table.rows[i].insertCell(1);
    table.rows[i].cells[1].className = "txt_medium_normal";
    table.rows[i].cells[1].innerHTML = "<a href=\"javascript:void(0)\" onClick=\"loadLayerData('get_user_details', 'layer1', true, '"+data[i]['user_id']+"')\">"+data[i]['player_name']+"</a>";
    
    table.rows[i].insertCell(2);
    table.rows[i].cells[2].className = "txt_medium_normal";
    table.rows[i].cells[2].innerHTML = data[i]['player_basename'];
  }
}

function loadUserDetails(userId)
{
  safeAgentCall('', 'get_user_details', 'showUserDetails', userId);
}

function showUserDetails(data)
{
  document.getElementById('user_details').innerHTML = data;
}

function addUserToFriends(userId)
{
  safeAgentCall('', 'add_user_to_friends', 'userToFriendsAdded', userId);
}

function userToFriendsAdded(status)
{
  document.getElementById('add_to_friends_status').innerHTML = status;
}

function activateFriendlyRequest(type, userId)
{
  safeAgentCall('', 'activate_friendly_request', 'friendlyRequestActivated', type, userId);
}

function friendlyRequestActivated(status)
{
  if(status['field'] != null)
    document.getElementById(status['field']).innerHTML = status['status'];
}

function removeBuddy(type, userId)
{
  safeAgentCall('', 'remove_buddy', 'buddyRemoved', type, userId);
}

function removeBuddyAll(userId)
{
  safeAgentCall('', 'remove_buddy', 'buddyRemovedBoth', "", userId);
}

function buddyRemoved(status)
{
  if(status != null)
  {
    var table = document.getElementById("buddy_list_table");
    table.deleteRow(document.getElementById(status).rowIndex);
  }
}

function buddyRemovedBoth(status)
{
  if(status != null)
    document.getElementById("remove_buddy_status").innerHTML = status;
}

function goToPlayerOrCountryTextBox(event)
{
  if(enterKeyPressed(event))
  {
    var query = document.getElementById('go_to_field').value;
    if(query != "")
      safeAgentCall('', 'go_to_player_or_country', 'goToPlayerOrCountryFeedback', query);
  }
}

function goToPlayerOrCountry()
{
  var query = document.getElementById('go_to_field').value;
  if(query != "")
    safeAgentCall('', 'go_to_player_or_country', 'goToPlayerOrCountryFeedback', query);
}

function goToPlayerOrCountryFeedback(status)
{
  if(status['type'] != null && status['type'] != "")
  {
    if(status['type'] == "country")
      window.location.href = window.location.protocol+"//"+window.location.hostname+":"+window.location.port+window.location.pathname+"?content=country&cid="+status['id'];
    else if(status['type'] == "player")
      window.location.href = window.location.protocol+"//"+window.location.hostname+":"+window.location.port+window.location.pathname+"?content=players&pid="+status['id'];
  }
  else
  {
    agent.call('', 'get_user_and_country_list', 'showLayerData', 'layer1', status['query'], 'go_to_field');
  }
}

function mouseDownTracker(e)
{
  if(document.all)
  {
  	mousePosX = event.x;
    mousePosY = event.y + document.body.scrollTop;
  }
  else
  {
  	mousePosX = e.pageX;
    mousePosY = e.pageY;
  }
}

function mouseMoveTracker(e)
{
  var mouseX, mouseY;
  
  if(document.all)
  {
  	mouseX = mousePosX - event.x;
    mouseY = mousePosY - (event.y + document.body.scrollTop);
  }
  else
  {
  	mouseX = mousePosX - e.pageX;
    mouseY = mousePosY - e.pageY;
  }
  /*if(lastLayer != "" && mouseX*mouseX + mouseY*mouseY > 10000)
  {
    document.getElementById(lastLayer).style.display = "none";
    lastLayer = "";
  }*/
}

function showImage(filename, title, imageWidth, imageHeight)
{
  var availWidth  = screen.availWidth - 26;
  var availHeight = screen.availHeight - 26;
  var windowName  = "escalations_screenshot";
  var viewerPage  = "viewer.php?filename=" + filename + "&title=" + title;
  
  if((availWidth < imageWidth) || (availHeight < imageHeight))
  {
    var parameters = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,left=0,top=0,width="+availWidth+",height="+availHeight;
  }
  else
  {
    var parameters = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,left="+((availWidth-imageWidth)/2)+",top="+((availHeight-imageHeight)/2)+",width="+imageWidth+",height="+imageHeight;
  }
  window.open(viewerPage, windowName, parameters);
}

function sendInvitation()
{
  var toAddress         = document.getElementById("to_address").value;
  var fromAddress       = document.getElementById("from_address").value;
  var invitationMessage = document.getElementById("invitation_message").value;
  
  document.getElementById("invitation_message_status").innerHTML = "";
  
  tickSafeAgentCall('', 'send_invitation', 'invitationSent', toAddress, fromAddress, invitationMessage);
}

function invitationSent(status)
{
  if(status != null)
    document.getElementById("invitation_message_status").innerHTML = status;
}

function setRankingsRound()
{
  var roundId = document.getElementById("current_round")[document.getElementById("current_round").selectedIndex].value;
  window.location.href = window.location.protocol+"//"+window.location.hostname+":"+window.location.port+window.location.pathname+"?content=rankings&rid="+roundId;
}
