// This file contains code in connection with the WMI2 Ajax communication

// Variables

var xml_http_request = false; // XMLHttpRequest object
var ajaxQueue = new Array();  // variable storing the ajax requests waiting to start
var ajaxLock = false;  // true if ajax request is on run
var ongoingrefresh = false;  // for ajaxRefreshImage
var nextrefresh = false;  // for ajaxRefreshImage
var refreshid;  // for ajaxRefreshImage
var refreshformula;  // for ajaxRefreshImage
var refreshdensity;  // for ajaxRefreshImage
var refreshcursor;  // for ajaxRefreshImage
var newLayoutHelp = false;  // for ajaxLoadLayout
var formulamessage = 'ezaz';  // for ajaxLoadNew
var ws_reallynewmess = "";  // for newWorksheet
var browserdetected = "";  // detect browser

// Code running at include: initalize Ajax (XMLHttp)
try {
  xml_http_request = new XMLHttpRequest();
} catch (ifie) {
  try {
    xml_http_request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (ifie2) {
    try {
      xml_http_request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (fail) {
      xml_http_request = false;
    }
  }
}
if (!xml_http_request)
  alert("Error in XMLHttpRequest initialization");

// detect browser - not perfect
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
  browserdetected = "Chrome";
else if (navigator.userAgent.toLowerCase().indexOf('safari') > -1)
  browserdetected = "Safari";
else if (navigator.userAgent.toLowerCase().indexOf('msie 8') > -1)
  browserdetected = "IE8";
else if (navigator.userAgent.toLowerCase().indexOf('msie') > -1)
  browserdetected = "IE";
else if (navigator.userAgent.toLowerCase().indexOf('opera') > -1)
  browserdetected = "Opera";
else if (navigator.vendor.toLowerCase().indexOf('kde') > -1)
  browserdetected = "Konqueror";
else if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
  browserdetected = "Firefox";
else if (navigator.userAgent.toLowerCase().indexOf('netscape') > -1)
  browserdetected = "Netscape";
else if (navigator.userAgent.toLowerCase().indexOf('gecko') > -1)
  browserdetected = "Mozilla";
else if (navigator.userAgent.toLowerCase().indexOf('mozilla') > -1)
  browserdetected = "Netscape";
else
  browserdetected = "unknown";

// Functions

// Checks if the server returned with the string [phperror]
function phpError(restext)
{
  var errorplace = restext.indexOf("[phperror]");
  if (errorplace == -1) {
    return false;
  } else {
    return true;
  }
}

// This is the main Ajax function, the others call this
function ajaxPostRequest(paramsx,handlerinx)
{
  document.body.style.cursor = "wait";
  switch (browserdetected) {
  case "IE8":
    xml_http_request.open("POST","main.php");
    break;
  case "IE":
  case "Konqueror":
    xml_http_request.open("POST","main.php",true);
    break;
  case "Opera":
    xml_http_request.open("POST","main.php",false);
    break;
  case "Firefox":
  case "Mozilla":
  case "Netscape":
  default:
    xml_http_request.open("POST","main.php");
    break;
  }
  xml_http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
  var onrsc = function() {
    if (xml_http_request.readyState == 4 && xml_http_request.status == 200) {
      if (phpError(xml_http_request.responseText)) {
        ajaxQueue.splice(0);
        document.body.style.cursor = "default";
        document.body.innerHTML = '<iframe width="100%" height="100%" src="error.php" frameborder="0">&nbsp;</iframe>';
        return;
      }
      document.body.style.cursor = "default";
      handlerinx(xml_http_request.responseText);
      var nextrequest = ajaxQueue.shift();
      if (nextrequest != null) {
        ajaxPostRequest(nextrequest[0],nextrequest[1]);
      } else {
        ajaxLock = false;
      }
    }
  }
  xml_http_request.onreadystatechange = onrsc;
  xml_http_request.send(paramsx);
}

// This function is responsible for starting all Ajax requests
function ajaxPostMain(params,handlerin)
{
  if ((ajaxLock == false)&&((xml_http_request.readyState == 4 && xml_http_request.status == 200)||(xml_http_request.readyState == 0))) {
    ajaxLock = true;
    ajaxPostRequest(params,handlerin);
  } else {
    ajaxQueue.push([params,handlerin]);
  }
}

// Load the colors of the calculator
function ajaxButtonType()
{
  ajaxPostMain(
    "postop=getbuttontypes",
    function(restext) {
      eval(restext);
    }
  );
}

// Preload the calculator button images
function ajaxLIPreload(layout)
{
  ajaxPostMain(
    "postop=lipreload&postpar="+layout,
    function(restext) {
      eval(restext);
      imagePreload(liarray);
      if (navigator.appName != "Netscape") {
        showLayout();
      }
    }
  );
}

// Refresh an input formula picture
// Don't start a refresh for every change if they are fast
function ajaxRefreshImage(imageid,formula,density,cursor)
{
  if (ongoingrefresh == false) {
    ongoingrefresh = true;
    theinputispink = false;
    ajaxPostMain(
      "postop=refresh&postpar="+formula+"&density="+density+"&cursor="+cursor,
      function(restext) {
        freshsaved = false;
        if (restext == "./image/fcex.png") {
          document.getElementById("theinput").style.backgroundColor = "pink";
          theinputispink = true;
        } else {
          document.getElementById("theinput").style.backgroundColor = "white";
          document.getElementById(imageid).src = restext;
        }
        ongoingrefresh = false;
        if (nextrefresh == true) {
          ajaxRefreshImage(refreshid,refreshformula,refreshdensity,refreshcursor);
          nextrefresh = false;
        }
      }
    );
  } else {
    refreshid = imageid;
    refreshformula = formula;
    refreshdensity = density;
    refreshcursor = cursor;
    nextrefresh = true;
  }
}

// Load a maxima output formula image to the worksheet
function ajaxLoadImage(whichid,formula,density,operation,opbutton)
{
  if (document.getElementById("codiv"+whichid))
    document.getElementById("codiv"+whichid).innerHTML = 
    "<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
  ajaxPostMain(
    "postop=calc&postpar="+formula+"&operation="+operation+"&density="+density+"&opbutton="+opbutton,
    function(restext) {
      freshsaved = false;
      document.getElementById("codiv"+whichid).innerHTML = restext;
      document.getElementById("codivt").id = "codivt"+whichid;
      document.getElementById("gethelp").id = "gethelp"+whichid;
      document.getElementById("co").name = "co"+whichid;
      document.getElementById("co").id = "co"+whichid;
      var cowh = function(event) {
        toCalcRes(whichid);
      }
      document.getElementById("co"+whichid).onclick = cowh;
      if (document.getElementById("gethelp"+whichid).style.display != "none")
        registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
    }
  );
}

// Loads a new 2D gnuplot image
function ajaxLoadPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar)
{
  var suffix = "";
  if ((browserdetected == "Chrome") || (browserdetected == "Safari") || (browserdetected == "Konqueror"))
    suffix = "_" + Math.abs(xmin).toFixed(2) + "_" + Math.abs(xmax).toFixed(2) + "_" + Math.abs(ymin).toFixed(2) + "_" + Math.abs(ymax).toFixed(2);
  if (document.getElementById("codiv"+whichid))
    document.getElementById("codiv"+whichid).innerHTML = 
    "<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
  ajaxPostMain(
    "postop=plot&postpar="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar+"&suffix="+suffix,
    function(restext) {
      freshsaved = false;
      document.getElementById("codiv"+whichid).innerHTML = restext;
      document.getElementById("gethelp").id = "gethelp"+whichid;
      if (document.getElementById("gethelp"+whichid).style.display != "none")
        registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
    }
  );
}

// Refresh an existing 2D gnuplot image (zooming)
function ajaxRefreshPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar)
{
  var suffix = "";
  if ((browserdetected == "Chrome") || (browserdetected == "Safari") || (browserdetected == "Konqueror"))
    suffix = "_" + Math.abs(xmin).toFixed(2) + "_" + Math.abs(xmax).toFixed(2) + "_" + Math.abs(ymin).toFixed(2) + "_" + Math.abs(ymax).toFixed(2);
  ajaxPostMain(
    "postop=rplot&postpar="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar+"&suffix="+suffix,
    function(restext) {
      freshsaved = false;
      eval(restext);
      var restext2c = restext2.replace(/\+/g," ");
      restext2c = unescape(restext2c);
      document.getElementById("comap"+whichid).innerHTML = restext2c;
      document.getElementById("copic"+whichid).useMap = "";
      document.getElementById("copic"+whichid).useMap = "#plotmap_"+whichid+suffix;
      document.getElementById("copic"+whichid).src = restext1;
      document.getElementById("copic"+whichid).setAttribute("title","");
      document.getElementById("unzoom"+whichid).onclick = restext3;
    }
  );
}

// Load a new complex plot image
function ajaxLoadCPlot(whichid,formula,xmin,xmax,ymin,ymax)
{
  var suffix = "";
  if ((browserdetected == "Chrome") || (browserdetected == "Safari") || (browserdetected == "Konqueror"))
    suffix = "_" + Math.abs(xmin).toFixed(2) + "_" + Math.abs(xmax).toFixed(2) + "_" + Math.abs(ymin).toFixed(2) + "_" + Math.abs(ymax).toFixed(2) + "_false";
  if (document.getElementById("codiv"+whichid))
    document.getElementById("codiv"+whichid).innerHTML = 
    "<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
  ajaxPostMain(
    "postop=cplot&postpar="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid=false&suffix="+suffix,
    function(restext) {
      freshsaved = false;
      document.getElementById("codiv"+whichid).innerHTML = restext;
      document.getElementById("gethelp").id = "gethelp"+whichid;
      var gridel = document.getElementById("grid");
      gridel.id = "grid"+whichid;
      gridel.name = "grid"+whichid;
      gridel.onclick = function(event) {
        ajaxRefreshCPlot(whichid,formula,xmin,xmax,ymin,ymax);
      }
      if (document.getElementById("gethelp"+whichid).style.display != "none")
        registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
    }
  );
}

// Refresh a complex plot image (zoom in, out)
function ajaxRefreshCPlot(whichid,formula,xmin,xmax,ymin,ymax)
{
  var grid = "false";
  if (document.getElementById("grid"+whichid).checked)
    grid = "true";
  var suffix = "";
  if ((browserdetected == "Chrome") || (browserdetected == "Safari") || (browserdetected == "Konqueror"))
    suffix = "_" + Math.abs(xmin).toFixed(2) + "_" + Math.abs(xmax).toFixed(2) + "_" + Math.abs(ymin).toFixed(2) + "_" + Math.abs(ymax).toFixed(2) + "_" + grid;
  ajaxPostMain(
    "postop=rcplot&postpar="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&suffix="+suffix,
    function(restext) {
      freshsaved = false;
      eval(restext);
      var restext2c = restext2.replace(/\+/g," ");
      restext2c = unescape(restext2c);
      document.getElementById("comap"+whichid).innerHTML = restext2c;
      document.getElementById("copic"+whichid).useMap = "";
      document.getElementById("copic"+whichid).useMap = "#plotmap_"+whichid+suffix;
      document.getElementById("copic"+whichid).src = restext1;
      document.getElementById("copic"+whichid).setAttribute("title","");
      document.getElementById("unzoom"+whichid).onclick = restext3;
      document.getElementById("grid"+whichid).onclick = function(event) {
        ajaxRefreshCPlot(whichid,formula,xmin,xmax,ymin,ymax);
      }
      var halfx = (restext4[0]+restext4[1])*0.5;
      var halfy = (restext4[2]+restext4[3])*0.5;
      var numform = restext4[0].toFixed(2);
      if (restext4[3]>=0)
        numform += "+";
      numform += restext4[3].toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a1").innerHTML = numform;
      numform = halfx.toFixed(2);
      if (restext4[3]>=0)
        numform += "+";
      numform += restext4[3].toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a2").innerHTML = numform;
      numform = restext4[1].toFixed(2);
      if (restext4[3]>=0)
        numform += "+";
      numform += restext4[3].toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a3").innerHTML = numform;
      numform = restext4[0].toFixed(2);
      if (halfy>=0)
        numform += "+";
      numform += halfy.toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a4").innerHTML = numform;
      numform = restext4[1].toFixed(2);
      if (halfy>=0)
        numform += "+";
      numform += halfy.toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a5").innerHTML = numform;
      var numform = restext4[0].toFixed(2);
      if (restext4[2]>=0)
        numform += "+";
      numform += restext4[2].toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a6").innerHTML = numform;
      numform = halfx.toFixed(2);
      if (restext4[2]>=0)
        numform += "+";
      numform += restext4[2].toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a7").innerHTML = numform;
      numform = restext4[1].toFixed(2);
      if (restext4[2]>=0)
        numform += "+";
      numform += restext4[2].toFixed(2);
      numform += "<i>i</i>";
      document.getElementById("coside"+whichid+"a8").innerHTML = numform;
    }
  );
}

// Load a new 3D gnuplot image
function ajaxLoad3DPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar,yangle,xangle)
{
  if (document.getElementById("codiv"+whichid))
    document.getElementById("codiv"+whichid).innerHTML = 
    "<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
  ajaxPostMain(
    "postop=plot3&postpar="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar+"&yangle="+yangle+"&xangle="+xangle,
    function(restext) {
      freshsaved = false;
      document.getElementById("codiv"+whichid).innerHTML = restext;
      document.getElementById("gethelp").id = "gethelp"+whichid;
      if (document.getElementById("gethelp"+whichid).style.display != "none")
        registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
    }
  );
}

// Refresh an existing 3D gnuplot image (zooming, rotation, ..)
function ajaxRefresh3DPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar,yangle,xangle)
{
  ajaxPostMain(
    "postop=rplot3&postpar="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar+"&yangle="+yangle+"&xangle="+xangle,
    function(restext) {
      freshsaved = false;
      eval(restext);
      document.getElementById("copic"+whichid).src = restext1;
      document.getElementById("unzoom"+whichid).onclick = restext3;
      document.getElementById("zoom"+whichid).onclick = restextin;
      document.getElementById("up"+whichid).onclick = restextup;
      document.getElementById("north"+whichid).onclick = restextnorth;
      document.getElementById("down"+whichid).onclick = restextdown;
      document.getElementById("south"+whichid).onclick = restextsouth;
      document.getElementById("left"+whichid).onclick = restextleft;
      document.getElementById("west"+whichid).onclick = restextwest;
      document.getElementById("right"+whichid).onclick = restextright;
      document.getElementById("east"+whichid).onclick = restexteast;
    }
  );
}

// Load a new calculator layout
function ajaxLoadLayout(layout)
{
  ajaxPostMain(
    "postop=cblayout&postpar="+layout,
    function(restext) {
      eval(restext);
      loadLayout("calcdiv");
      newLayoutHelp = true;
    }
  );
}

// Load the message connected to the calculator layout
function ajaxLayoutMessage(layout)
{
  ajaxPostMain(
    "postop=layoutmsg&postpar="+layout,
    function(restext) {
      document.getElementById("wtop").innerHTML = restext;
    }
  );
}

// Load a WMI2 message and do something with it
function ajaxMessage(message,funct)
{
  ajaxPostMain(
    "postop=message&postpar="+message,
    funct
  );
}

// Create a new entry on the worksheet
function ajaxLoadNew(whichid)
{
  ajaxPostMain(
    "postop=newl",
    function(restext) {
      if (whichid > 1) {
        var hr = document.createElement("hr");
        document.getElementById("workspace").appendChild(hr);
      }
      var uinputdiv = document.createElement("div");
      uinputdiv.setAttribute("id","uidiv"+whichid);
      document.getElementById("workspace").appendChild(uinputdiv);
      var uinputdivtext = document.createElement("div");
      uinputdivtext.setAttribute("id","uidivt"+whichid);
      uinputdivtext.style.display = "none";
      uinputdivtext.innerHTML = "..#";
      var coutputdiv = document.createElement("div");
      coutputdiv.setAttribute("id","codiv"+whichid);
      document.getElementById("workspace").appendChild(coutputdiv);
      var codivtext = document.createElement("div");
      codivtext.setAttribute("id","codivt"+whichid);
      codivtext.style.display = "none";
      codivtext.innerHTML = "..#";
      document.getElementById("codiv"+whichid).appendChild(codivtext);
      var pictext = '<div class="picdiv1"><div class="picdiv"><img name="ui'+whichid+
      '" id="ui'+whichid+'" class="uia" onclick="toCalc('+whichid+
      ')" src="./image/base.png" title="'+formulamessage+'" alt=\"'+formulamessage+'\"></div></div>';
      var reptext = restext.replace("[ui]",pictext);
      document.getElementById("uidiv"+whichid).innerHTML = reptext;
      document.getElementById("uidiv"+whichid).appendChild(uinputdivtext);
      document.getElementById("codiv"+whichid).innerHTML = "<br><br><br><br>";
      document.getElementById("codiv"+whichid).scrollIntoView(true);
    }
  );
}

// Load a calculator button group
function ajaxLoadGroup(grbutton,button,cx,cy)
{
  ajaxPostMain(
    "postop=cbgroup&postpar="+grbutton,
    function(restext) {
      if (grouplock2 == false) {
        eval(restext);
        loadGroup(button,cx,cy);
      }
      grouplock = false;
    }
  );
}

// Set the language of WMI2
function ajaxSetLanguage(language)
{
  ajaxPostMain(
    "postop=lang&postpar="+language,
    function(restext) {
      if (restext.substr(0,2) == "ok") {
        var restsp = restext.split(";;;");
        document.getElementById("refreshhintid").setAttribute("title", restsp[1]);
        document.getElementById("newhintid").setAttribute("title", restsp[2]);
        document.getElementById("savehintid").setAttribute("title", restsp[3]);
        document.getElementById("printhintid").setAttribute("title", restsp[4]);
        document.getElementById("helphintid").setAttribute("title", restsp[5]);
        document.getElementById("paypalhintid").setAttribute("title", restsp[6]);
        befunloadmess = restsp[7];
        document.getElementById("copyright").innerHTML = restsp[8];
        ws_reallynewmess = restsp[9];
      } else {
        alert(restext);
      }
    }
  );
}

// Load the helpdiv (for teacher advertisements)
function ajaxHelpContent(whichid,xsign)
{
  ajaxPostMain(
    "postop=help",
    function(restext) {
      document.getElementById(whichid).innerHTML = restext;
      document.getElementById("xin").appendChild(xsign);
    }
  );
}

// Load the popup window of a teacher
function ajaxPopupTeacher(teacher,ip,showed)
{
  var tw = window.open('','tw','height=250,width=600,scrollbars=yes');
  ajaxPostMain(
    "postop=teacher&postpar="+teacher+"&ip="+ip+"&showed="+showed,
    function(restext) {
      tw.document.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n');
      tw.document.write('            "http://www.w3.org/TR/html4/loose.dtd">\n');
      tw.document.write('<html><head>\n');
      tw.document.write('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n');
      tw.document.write('<link rel="stylesheet" type="text/css" href="css/popup.css">\n');
      tw.document.write('<title>matek.hu</title>\n');
      tw.document.write('</head><body>\n');
      tw.document.write(restext);
      tw.document.write('</body></html>\n');
      tw.document.close();
    }
  );
}

// Load all teachers of a city (used by teachers.php)
function ajaxAllTeacherCity(city)
{
  ajaxPostMain(
    "postop=allteacher&postpar="+city,
    function(restext) {
      document.getElementById("rightdiv").innerHTML = restext;
    }
  );
}

function ajaxPing(funct1)
{
  ajaxPostMain(
    "postop=ping",
    funct1
  );
}

