// copyright ============================================================================//
// copyright 2002 / 2003
// leen besselink && sander prins && jan vermaat
// copyright ============================================================================//

var xmlObj  = false;
// de constructor functie voor de instance ===============================================//

function xml() {
	// welk type XML OBJECT
	this.typecomobject = "Microsoft.XMLHTTP"
	// welk type XMLDOM
	this.typeDOMobject = "Microsoft.XMLDOM"
	// doe dit type request ale er niets anders meer mogelijk is
	this.standartRequesttype = 'text/html'
	//default waarde wat voor een soort response verwacht ik?
	this.default_responsetype = "xml";	
	//default waarde wat voor een soort request type verstuur ik?
	this.default_requesttype = "text/xml";	
	//debug-info variabele zetten . True: dit geeft een alert box met de response van de server
	this.default_debug = false;
	// waar moet de request naar toe?
	this.default_URL = "http://" + document.domain + "/p3.php";
	// wat is de default processName?
	this.default_mapping = "/mappings/descriptor/";
	//
	// de volgende waarden worden gezet in xml.prototype.overrule()
	// de gebruiker kan de default waarden overrulen door de method request(mapping, URL, responsetype, requesttype,  debug) met de nodige parameters aan te roepen
	this.mapping	 	= false;
	this.URL 			= false;
	this.responsetype 	= false;		
	this.requesttype 	= false;
	this.debug			= false;

	
	// einde deze waarden worden gezet in xml.prototype.overrule()
	//
	// in het responseObject komen de waarden de de server terug geeft
	this.responseObject = new Object();
	/* mogelijke waarden van deze property:
		responseObject.contenttype 		: contenttype uit de http-header
		responseObject.responsetype 	: gewenste type output (nu: xml of html)
		responseObject.path				: het path waar het verzoek naartoe is gestuurd
		responseObject.responsetext		: tekst die terugkomt
		responseObject.responsexml		: xml object dat terugkomt
		responseObject.status			: status
		responseObject.statustext 		:statustekst (OK)
		Deze waarden worden gezet in xml.prototype.dataConnection(), al naar gelang het soort response dan van de server komt
	*/
	//
	// zet de XML HTTP connectie op
	this.connection = new xmlinit (this.typecomobject, this.typeDOMobject);
	
}

// haal de data op =======================================================================//
// haal de data op middels dataConnection()
/*
input:
mapping : optioneel: naam van de severside mapping (b.v. /mappings/rollen/)
URL: optioneel: de aanroep van de server (b.v. http://www.pagelink.nl)
responsetype: optioneel: welk type response verwacht ik (xml / html)
requesttype: welk type request verstuur ik (xlm / html)
argName: ?? [uitzoeken]
debug: zet debug info aan
*/
xml.prototype.request = function (mapping, id, URL, responsetype, requesttype, debug) {
	// overrule evenueel de default waarden
	this.overrule (mapping, responsetype, requesttype, debug,  URL);
	// einde overrule evenueel de default waarden
	switch (this.responsetype) {
		case 'xml':
			XMLDomDoc = this.buidXMLRequest (id);
			this.dataConnection (XMLDomDoc);
			break;
		default :
			this.dataConnection ();
			break;
	}
	// de data is nu opgehaald. Bekijk nu wat er mee gedaan moet worden...
	return this.dispatchData();
}


/*  buidXMLRequest =========================================================================//
bouw een XML request
maak een XMLDOMDocument
*/
xml.prototype.buidXMLRequest = function  (id) {
	if (!this.mapping) {
		return false;
	}
	x = new xmlrequest();
	xmlDomDoc = false;
	switch (this.mapping) {
		case '/mappings/rollenbeheer/':
			break;
		case '/mappings/get_bouwsteenproperties/':
			xmlDomDoc = x.get_BouwsteenProperties (id);
			break;
		case '/mappings/set_bouwsteenproperties/':
			xmlDomDoc = x.set_BouwsteenProperties (id);
			break;
		case '/mappings/del_bouwsteenproperties/':
			xmlDomDoc = x.del_BouwsteenProperties (id);
			break;
		case '/mappings/descriptor/':
			xmlDomDoc = x.create_Request_Descriptor();
			break;
		default :
	}
	return xmlDomDoc;
}

/* de eigenlijke dataconnectiom ==========================================================//
method dataConnection
description: haalt data op met het xmlhttp-object
input : 
	path = het pad naar het gevraagde bestand
	output: object
*/

xml.prototype.dataConnection = function (XMLDOMDocument, callback) {
	if (callback)
		this.callback = callback;

	var connection = this.connection;

	if (!connection)
		return false;
	try {

		var myObj = this;

		connection.myreadystatechange = function () {
			// [LB]
			// in Mozilla:	'this' is the function (which was usefull)
			// in IE:	'this' is document (which is useless)
			// but I am inside the scope of the request object somehow and myObj is unique
			// it's strange, but I'm starting to understand, little, by little

			if (typeof connection.xmlhttp != 'undefined')
//				leeninspect (connection.xmlhttp.readyState);
				if (connection.xmlhttp.readyState == 4) {
					connection.xmlhttp.onreadystatechange = function () {};

					myObj.responseObject.contenttype 		= connection.xmlhttp.getResponseHeader('Content-Type');
					myObj.responseObject.url 				= connection.url;
					myObj.responseObject.status				= connection.xmlhttp.status;
					myObj.responseObject.statustext 		= connection.xmlhttp.statusText;

					try {
						var type = typeof connection.xmlhttp.responseText;
					} catch (e) {
						var type = false;
					}

					if (type == 'string') {
						myObj.responseObject.responsetext		= connection.xmlhttp.responseText;// unescape(loader.xmlhttp.responseText);

						if (typeof connection.xmlhttp.responseXML == 'undefined')
							myObj.responseObject.responsexml	= false;
						else
							myObj.responseObject.responsexml	= connection.xmlhttp.responseXML;
					} else {
						myObj.responseObject.responsexml = false;
						myObj.responseObject.responsetext = connection.xmlhttp.responseBody;
					}

					if (typeof myObj.callback == 'function')
						myObj.callback (myObj.responseObject);
				}
		}

		connection.xmlhttp.onreadystatechange = connection.myreadystatechange;

		connection.xmlhttp.open("POST", this.URL , true)
		switch (this.default_requesttype) {
			case 'text/xml':
				connection.xmlhttp.setRequestHeader ('Content-type', this.requesttype);
				break;
			default:
				connection.xmlhttp.setRequestHeader ('Content-type', this.standartRequesttype);
		}
		connection.xmlhttp.send("<?xml version=\"1.0\"?>" + XMLDOMDocument.xml);

/*
		if (connection.readyState != 4)	return false;
		this.responseObject.contenttype 	= connection.getResponseHeader('Content-Type');
		this.responseObject.responsetype 	= this.responsetype;
		this.responseObject.path 			= this.URL;
		this.responseObject.responsetext	= unescape(connection.responseText);
		this.responseObject.responsexml		= connection.responseXML;
		this.responseObject.status			= connection.status;
		this.responseObject.statustext 		= connection.statusText;
*/
		return true;
	
	} catch(e) {
		alert('Foutsituatie : kan geen connectie met de server maken...');
		return false;
	}
}

// de dispatchfuncties voor het ontvangen van XML ======================================//
//
// dispatch de opgehaalde XML code, per proces ==========================================//
xml.prototype.dispatchXMLData = function () {
	switch(this.mapping) {
		case '/mappings/descriptor/':
			return this.writePWS (this.fieldName);
			break;
		case '/mappings/get_bouwsteenproperties/':
			nb = new bsClass();
			nb.xml = this.responseObject.responsexml;
			nb.parseXML();
			break;
		case '/mappings/set_bouwsteenproperties/':
			nb = new bsClass();
			nb.xml = this.responseObject.responsexml;
			nb.parseXML_Action();
//			document.body.innerHTML+="<textarea style=\"width:800;height:300;z-index:1000000\">" + nb.xml.xml + "</textarea>";
			break;
		case  '/mappings/del_bouwsteenproperties/':
			nb = new bsClass();
			nb.xml = this.responseObject.responsexml;
			nb.parseXML_Action();
			break;
		default:
//			document.body.innerHTML+="<textarea style=\"width:800;height:300;z-index:1000000\">" + nb.xml.xml + "</textarea>";
			return false;
	
	}
}
// =======================================================================================//

// dispatch de opgehaalde XML of HTML code ===============================================//
xml.prototype.dispatchData = function () {
	var regEx = new RegExp(this.responseObject.responsetype, "i")
		if (this.debug)
		alert('[182 xml.js] response\n\n' + this.responseObject.responsetext );
		if (regEx.test(this.responseObject.contenttype)){
		switch(this.responseObject.responsetype){
			case 'xml':
				//if (this.debug)
				//	 alert('[182 xml.js] response\n\n' + this.responseObject.responsetext );
				return this.dispatchXMLData ();
				break;
			case 'html':
				returnStr = this.responseObject.responsetext;
				if (this.debug)
					 alert(returnStr);
				return returnStr;
				break;
			default: 
				return "ERROR: response type [97 xml.js]";
		}
	} else {
		return "ERROR: request type [100 xml.js]";
	}
}

// ===============================================================================//
// de PWS descriptor-build functies ==============================================//
// writePWS 
// start de core functie voor het bouwen van PWS van uit de PWS-descriptor
xml.prototype.writePWS = function (type){
	treeObject = this.responseObject.responsexml
		if (treeObject && pp3Window) {
		pp3Window.debug ("addStandardWindow:<br><textarea style=\"width:490;height:300\">" + treeObject.xml + "</textarea><br>\n" )
		this._writePWS (treeObject)
	}
	return true;
}


// _writePWS =====================================================================//

// loop de gehele PWS-descriptor door door en bouw de PWS omgeving
// de core functie
xml.prototype._writePWS = function (treeObject) {
	if (treeObject.hasChildNodes()){
		for(var i=0; i < treeObject.childNodes.length; i++){
			var myNodename = treeObject.childNodes[i].nodeName
			if (treeObject.childNodes[i].nodeType == 3) {
				// tekst
				// doe niks
				// pp3Window.debug ("xmltree: TEXT ::" +  treeObject.childNodes[i].text + "<br>")
			} else {
				var attributes = treeObject.childNodes[i].attributes;
				var title = this.getAttributeByName('title', attributes);
				var id =  this.getAttributeByName('id', attributes);
				var type =  this.getAttributeByName('type', attributes);
				var x = this.getAttributeByName('x', attributes);
				var y = this.getAttributeByName('y', attributes);
				var w = this.getAttributeByName('w', attributes);
				var h = this.getAttributeByName('h', attributes);
				var screensrc = this.getAttributeByName('screensrc', attributes);
				var datasrc = this.getAttributeByName('datasrc', attributes);
				
				if (myNodename == 'canvas') {
					this.canvastitle = title;
					this.canvasid = id;
					document.canvasTitle(this.canvasid, this.canvastitle);
				}
				if (myNodename == 'container') {
					pp3Window.debug ("document.addStandardWindow ('"+ this.canvastitle +"', '"+id+"', "+x+", "+y+", "+w+", "+h+");<br>")
					switch (type) {
						case 'standard':
							document.addStandardWindow ( this.canvasid, id, x, y, w, h);
							document.getContainerById(id).title(title);
							break;
						case 'canvastytle':
							break;
					}
				}
				if (myNodename == 'tabrow') {
					this.tabrowtitle = title;
					this.tabrowid = id;
					document.addTabWindow(this.canvasid, this.tabrowid, x, y, w, h);
				}
				if (myNodename == 'tabcontainer') {
					document.getContainerById(this.tabrowid).addTabContainer(id, h);
				}
				
			}
			if (treeObject.childNodes[i])
				this._writePWS(treeObject.childNodes[i]);
		}
	}
}

// getAttributeByName ===========================================================//
// vind een arttribuut in een enkele node
xml.prototype.getAttributeByName  = function (name, object) {
	name = name.toLowerCase();
	if (object.getNamedItem(name) != null)
		return object.getNamedItem(name).nodeValue;
	else
		return false;
}
// Einde van de PWS descriptor-build functies=====================================//
// ===============================================================================//


/*
function overrule ================================================================//
overrule indien nodig de waarde zoals die in xml() zijn gezet
*/
xml.prototype.overrule = function(mapping, responsetype, requesttype, debug,  URL){
	if (mapping) this.mapping = mapping;
	else  this.mapping = this.default_mapping;
	if (debug) this.debug = debug;
	else  this.debug = this.default_debug;
	if (responsetype) this.responsetype = responsetype;
	else this.responsetype = this.default_responsetype;
	if (requesttype) this.requesttype = requesttype;
	else this.requesttype = this.default_requesttype;
	if (URL) this.URL = URL;
	else this.URL = this.default_URL;
}



/* function xmlinit ======================================================================//
description: maak een instance van XMLHTTP-object aan. Een constructor functie
input: naam van het om object
output: geen
*/
function xmlinit(http, dom){
	if (window.ActiveXObject) {
		//ie5++
		try {
			this.typecomobject = 'Msxml2.XMLHTTP';
			this.xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {	}

		if (!this.xmlhttp) {
			try {
				this.typecomobject = 'Microsoft.XMLHTTP';
				this.xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {	}
		}
		this.xmldom = new ActiveXObject (dom);
	 } else 
		// NS6++ (niet getest)
		this.xmlhttp = new XMLHttpRequest();
}


xml.prototype.test = function () {
	alert("XML object loaded...");
}

