window.onload = prepareLinks;

function prepareLinks() {
  if (!document.getElementById || !document.getElementsByTagName) {
    return;
  }
 if (!document.getElementById("next-feature")) return;
  var el = document.getElementById("next-feature");
    el.onclick = function() {
      var query = this.getAttribute("href").split("?")[1];
      var url = "/wp-content/themes/serlo/functions/ajaxQuotes.php?"+query;
      return !grabFile(url);
	
  }
 /*
 // ADD AJAX FOR THE MP3 PLAYER
 if (!document.getElementById("listen-link")) return;
  var el2 = document.getElementById("listen-link");
    el2.onclick = function() {
      var url = this.getAttribute("href");
      return !grabFile(url);
	
  }*/
}
function grabFile(file) {
  var request = getHTTPObject();
  if (request) {
    request.onreadystatechange = function() {
      parseResponse(request);
    };
    request.open("GET", file, true);
    request.send(null);
    return true;
  } else {
    return false;
  }
}

function parseResponse(request) {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      var feature = document.getElementById("feature");
      feature.innerHTML = request.responseText;
	  //also change the query string
	    var thelink = document.getElementById("next-feature");
		var randnum = Math.random()*18;
		
		randnum = Math.round(randnum);
    	thelink.href = "/functions/ajaxQuotes.php?nextFeature=" + randnum;
		query = thelink.getAttribute("href").split("?")[1];
		
    }
  }
}

function getHTTPObject() {
  var xhr = false;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        xhr = false;
      }
    }
  }
  return xhr;
}