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

// initalize Ajax (XMLHttp)
var xml_http_request = false;
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");

// variable storing the ajax requests waiting to start
var ajaxQueue = new Array();
var ajaxLock = false;

// This function is called when the server returns 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";
    if (navigator.appName == "Microsoft Internet Explorer" || 
        navigator.appName == "Konqueror") {
    	xml_http_request.open("POST","main.php",true);
    } else if (navigator.appName == "Opera") {
    	xml_http_request.open("POST","main.php",false);
    } else { // "Netscape"
    	xml_http_request.open("POST","main.php");
    }
    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 = "auto";
		document.body.innerHTML = '<iframe width="100%" height="100%" src="error.php" frameborder="0">&nbsp;</iframe>';
		return;
	    }
	    document.body.style.cursor = "auto";
    	    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]);
    }
}

// This function calls the server with params, and puts the result in element
function ajaxHTML(elementid,params)
{
    ajaxPostMain(
	params,
	function(restext) {
	    var element = document.getElementById(elementid);
            element.innerHTML = restext;
        }
    );
}

// This function loads the colors of the calculator
function ajaxButtonType()
{
    ajaxPostMain(
	"getbuttontypes=true",
	function(restext) {
	    eval(restext);
	}
    );
}

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

// variables for ajaxRefreshImage
var ongoingrefresh = false;
var nextrefresh = false;
var refreshid;
var refreshformula;
var refreshdensity;
var refreshcursor;
// This function refreshes an input formula picture
function ajaxRefreshImage(imageid,formula,density,cursor)
{
    if (ongoingrefresh == false) {
	ongoingrefresh = true;
	theinputispink = false;
        ajaxPostMain(
	    "refresh="+formula+"&density="+density+"&cursor="+cursor,
	    function(restext) {
	        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;
    }
}

// This function loads an output formula image to the worksheet
function ajaxLoadImage(whichid,formula,density,operation,opbutton)
{
    document.getElementById("codiv"+whichid).innerHTML = 
	"<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
    ajaxPostMain(
	"calc="+formula+"&operation="+operation+"&density="+density+"&opbutton="+opbutton,
	function(restext) {
	    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;
	    registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
	}
    );
}

// This funtion loads a new 2D gnuplot image
function ajaxLoadPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar)
{
        document.getElementById("codiv"+whichid).innerHTML = 
	"<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
	ajaxPostMain(
	    "plot="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar,
	    function(restext) {
		document.getElementById("codiv"+whichid).innerHTML = restext;
		document.getElementById("gethelp").id = "gethelp"+whichid;
		registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
	    }
	);
}

// This function refreshes an existing 2D gnuplot image (zooming)
function ajaxRefreshPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar)
{
    ajaxPostMain(
	"rplot="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar,
	function(restext) {
            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;
	    document.getElementById("copic"+whichid).src = restext1;
	    document.getElementById("unzoom"+whichid).onclick = restext3;
	}
    );
}

// This function loads a new complex plot image
function ajaxLoadCPlot(whichid,formula,xmin,xmax,ymin,ymax)
{
    document.getElementById("codiv"+whichid).innerHTML = 
	"<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
    ajaxPostMain(
        "cplot="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax,
	function(restext) {
	    document.getElementById("codiv"+whichid).innerHTML = restext;
	    document.getElementById("gethelp").id = "gethelp"+whichid;
//	    registerTimedLink("gethelp"+whichid,"extraHelpDivOpen",200);
        }
    );
}

function ajaxRefreshCPlot(whichid,formula,xmin,xmax,ymin,ymax)
{
    ajaxPostMain(
	"rcplot="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax,
	function(restext) {
            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;
	    document.getElementById("copic"+whichid).src = restext1;
	    document.getElementById("unzoom"+whichid).onclick = restext3;
	}
    );
}

// This function loads a new 3D gnuplot image
function ajaxLoad3DPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar,yangle,xangle)
{
    document.getElementById("codiv"+whichid).innerHTML = 
	"<br><br><center><img src=\"./image/ajax-loader.gif\" alt=\"\"></center><br><br><br><br>";
    ajaxPostMain(
	"plot3="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar+"&yangle="+yangle+"&xangle="+xangle,
	function(restext) {
	    document.getElementById("codiv"+whichid).innerHTML = restext;
	}
    );
}

// This function refreshes an existing 3D gnuplot image (zooming, rotation, ..)
function ajaxRefresh3DPlot(whichid,formula,xmin,xmax,ymin,ymax,grid,ispar,yangle,xangle)
{
    ajaxPostMain(
	"rplot3="+formula+"&fid="+whichid+"&xmin="+xmin+"&xmax="+xmax+"&ymin="+ymin+"&ymax="+ymax+"&grid="+grid+"&ispar="+ispar+"&yangle="+yangle+"&xangle="+xangle,
	function(restext) {
            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;
	}
    );
}


var newLayoutHelp = false;
// This function loads a new calculator layout
function ajaxLoadLayout(layout)
{
    ajaxPostMain(
	"cblayout="+layout,
	function(restext) {
	    eval(restext);
	    loadLayout("calcdiv");
	    newLayoutHelp = true;
//	    AMtranslated = false;
//	    AMnoMathML = false;
//	    mathcolor = "";
//	    translate();
	}
    );
}

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

// This function loads a WMI2 message and do something with it
function ajaxMessage(message,funct)
{
    ajaxPostMain(
	"message="+message,
	funct
    );
}

var formulamessage = 'ezaz';
// This function creates a new entry on the worksheet
function ajaxLoadNew(layout,whichid)
{
    ajaxPostMain(
	"newl="+layout,
	function(restext) {	// FIXME: Opera, Konqueror works or not?
	    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);
	}
    );
}

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

// This function sets the language of WMI2
function ajaxSetLanguage(language)
{
    ajaxPostMain(
	"lang="+language,
	function(restext) {
	    alert(restext);
	}
    );
}

// This function loads the helpdiv
function ajaxHelpContent(whichid,xsign)
{
    ajaxPostMain(
	"help=true",
	function(restext) {
	    document.getElementById(whichid).innerHTML = restext;
	    document.getElementById("xin").appendChild(xsign);
	}
    );
}

// This funtion loads the popup window of a teacher
function ajaxPopupTeacher(teacher,ip,showed)
{
    var tw = window.open('','tw','height=250,width=600,scrollbars=yes');
    ajaxPostMain(
	"teacher="+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();
	}
    );
}

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