// loadXML.js
// Javascript functions used by the tutorial pages of linuxzoo.net
// Date    Author Prupose
// 21Dec04 AJC    Fix user name and password so that the values in the top right
//                get copied into hidden variables when check is done

function getXMLResponse(t,ci,addr){
  setDisplayWorking(ci);
  if (!addr) addr = "tut.cgi";
  addr += "?";
  //var a = new Array("xml","check","user","password");
  t.form["user"].value = document.forms["user"].elements["user"].value;
  t.form["password"].value = document.forms["user"].elements["password"].value;
  for (var i=0;i<t.form.elements.length;i++){
    addr += t.form.elements[i].name + "=" + encodeURIComponent(t.form.elements[i].value) + "&";
  }

  xmlLoadDoc(addr,cbFun);
  return false;
}

function cbFun(xdoc){
//Call back function - this happens when xdoc has been retrieved
//(well subject to the following test for IE)

  if (( window.ActiveXObject && /Win/.test(navigator.userAgent) )
	 && xdoc.readyState != 4) return;
		 //IE calls several times
  //alert(xdoc.documentElement.tagName);
  var elem = xdoc.documentElement;

  // if XMLHttpRequest
  if ((!elem)&&(xdoc.responseXML)&&(xdoc.responseXML.documentElement)) {
     elem = xdoc.responseXML.documentElement;
     // xdoc.status==200
     //alert(xdoc.responseText);
  }
  if (!elem){
    alert("XML document returned with no content.");
    return;
  }
  var ci = elem.getAttribute("check");
  caption = document.getElementById('cap'+ci);
  if (elem.firstChild.nodeName == "error"){
    caption.replaceChild(document.createTextNode("Tests: Incomplete ("+
          elem.firstChild.getAttribute("prob")+" problem)"),
       caption.firstChild);
    var msg = "There was a problem and we were unable to complete the tests.\n\n";
    if (elem.firstChild.getAttribute("prob")=="host")
      msg = "The tests could not be completed.\n"+
            "We were unable to find to your virtual machine.\n"+
            "You must obtain a virtual machine to continue.\n"+
            "Visit http://linuxzoo.net to book a virtual machine.\n\n";
    if (elem.firstChild.getAttribute("prob")=="connection"){
      msg = "The tests could not be completed.\n"+
 	    "We found your virtual machine but unable to connect\n"+
	    "to it; perhaps it is not running.\n"+
 	    "You must boot your virtual machine to continue.\n"+
	    "Visit http://linuxzoo.net to boot your virtual machine.\n\n";
    }
    if (elem.firstChild.getAttribute("prob")=="login")
      msg = "The tests could not be completed.\n"+
	    "Your virtual machine is running but we could not log in.\n"+
	    "You must set up an account to allow us to log in to run\n"+
	    "our tests - please supply the details of an account we\n"+
	    "can use.\n"+
	    "Some tests may require the root account to be given.\n\n";
    if (elem.firstChild.getAttribute("prob")=="target")
      msg = "The tests could not be completed.\n"+
            "Each tutorial is designed for a small set of operating\n"+
            "systems. This tutorial is not compatible with the one\n"+
            "you are currently running.\n\n";

    msg += elem.firstChild.firstChild.data;
    //document.getElementById("detail"+ci).style.display='block';
    var ddetail = document.getElementById("ddetail"+ci);
    if (ddetail.firstChild)
	ddetail.removeChild(ddetail.firstChild);
    //ddetail.appendChild(document.createTextNode(msg));
    alert(msg);
    return;
  }
  var checks = elem.getElementsByTagName("check");
  for (var i=0;i<checks.length;i++){
    setDisplay(ci-1,i, checks[i].getAttribute("pass"));
  }
  setScores(ci-1,elem.getAttribute("newscore"));
}

function setDisplayWorking(ci){
  //Set the display to indicate we are waiting for a result
  var caption;
  caption = document.getElementById('cap'+ci);
  caption.replaceChild(document.createTextNode("Tests: Working..."),
	caption.firstChild);
  var span;
  for (var i=1;span=document.getElementById("spanc"+ci+":"+i);i++){
    span.replaceChild(document.createTextNode("WORKING"),span.firstChild);
    span.style.backgroundColor = "gray";
  }
}

function setDisplay(c,i,pass){
  // Called when return from xml - also called from onload to initialise
  // previous
  var passStr = pass?"PASSED":"FAILED";
  var ci = c+1;
  var ip = i+1;
  caption = document.getElementById('cap'+ci);
  caption.replaceChild(document.createTextNode("Tests: Complete"),
        caption.firstChild);
  var span = document.getElementById("spanc"+ci+":"+ip);
  if (span){
    //span.replaceChild(document.createTextNode(passStr),span.firstChild);
    span.firstChild.nodeValue = passStr;
    span.style.backgroundColor = (pass)?"green":"red";
  }
}

function setScores(a,b,c){
  // Called during initialisation
  a = a*1+1;
  var frm = document.getElementById("cs"+a);
  if (frm){
    frm.firstChild.nodeValue = b;
  }
  //else
  //  alert("Debug current score: a:"+a+" b:"+b+ " c:" + c);

  frm = document.getElementById("bs"+a);
  if (frm)
    if (c)
      frm.replaceChild(document.createTextNode(c),frm.firstChild);
    else
      frm.firstChild.nodeValue = Math.max(frm.firstChild.nodeValue,b);
  //else
  //  alert("Debug best score: a:"+a+" b:"+b+ " c:" + c);
}

function setCGI(a,b,c){
  // Called during initialisation
  var frm = document.getElementById("frm_"+a);
  //alert("a:"+a+" b:"+b + " c:" + c);
  if (frm && frm.elements && frm.elements[b])
    frm.elements[b].value = c;
  //else
    //alert("Debug: a:"+a+" b:"+b+ " c:" + c);
}

function toggle(i){
  var d = document.getElementById(i);
  if (d){
    d.style.display = (d.style.display=="none")?"block":"none";
  }
}

//
// New version of xml load to take into account chrome
//
function xmlLoadDoc (file,cbFun) {
  var error = "";
  try //Internet Explorer
  {
   xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
   xmlDoc.async=true;
   xmlDoc.load(file);
   xmlDoc.onreadystatechange = function(){cbFun(xmlDoc)};
   return true;
  }
  catch(e)
  {
   try //Firefox, Mozilla, Opera, etc.
   {
    xmlDoc=document.implementation.createDocument("","",null);
    xmlDoc.async=true;
    xmlDoc.load(file);
    xmlDoc.onload = function(){cbFun(xmlDoc)};
    return true;
   }
   catch(e)
   {
    try //Google Chrome
    {
     var xmlhttp = new window.XMLHttpRequest();
     xmlhttp.open("GET",file,true);
     xmlhttp.onreadystatechange = function(){
       if (xmlhttp.readyState==4) {
         cbFun(xmlhttp);
       }
     };
     xmlhttp.send(null);
     //xmlDoc = xmlhttp.responseXML.documentElement;
     return true;
    }
    catch(e)
    {
     error=e.message;
    }
   }
  }
  return false;
}


