var http  = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var target = null;

function loadGames(obj) {
  if(obj.options.length < 2 && (http.readyState == 0 || http.readyState == 4)) {
    target = obj;
    http.open('get', '/ajax/loadAllGames.php');
    http.onreadystatechange = updateAllGames;
    http.send(null);
    target.options[1] = new Option('Loading games...', '');
  }
}

function updateAllGames() {
  if(http.readyState == 4 && http.status == 200) {
    target.options.length = 0;
    target.options[0] = new Option('Jump to a game...', '');

    var options = http.responseXML.getElementsByTagName('game');
    for(i = 0; i < options.length; i++) {
      target.options[target.options.length] = new Option(options[i].getAttribute('g_title'), options[i].getAttribute('g_url'));
    }
  }
}

function gotoGame(obj) {
  document.location.href = '/' + obj.value + '.html';
}

function showLoginForm() {
  document.getElementById('loginregister').style.display = 'none';
  document.getElementById('login').style.display = 'block';
  fadeIn('login', 0, 100, 500);
}

function checkLogin(form) {
  if(http.readyState == 0 || http.readyState == 4) {
    var data = 'username=' + form.elements['username'].value + '&password=' + form.elements['password'].value;
    http.open('get', '/login.php?' + data);
    http.onreadystatechange = verifyLogin;
    http.send(data);
  }  
}

function verifyLogin() {
  if(http.readyState == 4 && http.status == 200) {
    if(http.responseText == 'TRUE') {
      if(document.location.href.match('login.php')) {
        document.location.href = '/';
      } else {
        document.location.href = document.location.href;
      }
    } else {
      alert('Invalid username or password.');
    }
  }
}

function fadeIn(id, opacStart, opacEnd, millisec) { 
  //speed for each frame 
  var speed = Math.round(millisec / 85); 
  var timer = 0; 

  if(opacStart < opacEnd) { 
    for(i = opacStart; i <= opacEnd; i++) {
      setTimeout("animateFade(" + i + ",'" + id + "')", (timer * speed)); 
      timer++;
    } 
  } 
} 

function animateFade(opacity, id) { 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")";
}

function rate(game, rating) {
  var obj = document.getElementById('rating');
  obj.innerHTML = 'Sending vote...';

  var url = '/rate.php?g_id=' + game + '&rating=' + rating;
  http.open('get', url);
  http.onreadystatechange = ratingResponseHandler;
  http.send(null);
}

function ratingResponseHandler() {
  if(http.readyState == 4) {
    var obj = document.getElementById('rating');
    if(http.status == 200) {
      obj.innerHTML = http.responseText;
    } else {
      obj.innerHTML = 'Error!';
    }
  }
}

