/* **************************************************************** *///// JavaScript name: 	JavaScript: Ajax Common//						// function:		defines a collection of common Ajax functions into a single library//// usage:			//// created by:      rw//// created:			2009-07-06//// inputs://// outputs://// last modified:	//					2009--07-16 pb//					added jsLookup//// functions:///* **************************************************************** */var javaScriptLibraryName; /* global for errorLog */var SHOW_ERRORS = true;  /* remove after debug */javaScriptLibraryName = "JavaScript: Ajax Common";var globalArray;// alert(javaScriptLibraryName);var lookupType;	// used to change how we send the outputvar viewColumn;	// used to return the right column number// since there is no XMLHttpRequest JavaScript object in IE (until7), create one.// this way, you can create a new object with new XMLHttpRequest() regardless of the browser.if (!window.XMLHttpRequest && window.ActiveXObject) {	window.XMLHttpRequest = function() {		// try newest version first, then second newest ...		var versions = ['MSXML2.XMLHTTP.8.0', 'MSXML2.XMLHTTP.7.0', 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];		for (var i = 0; i < versions.length; i++) {			try {				return new ActiveXObject(versions[i]);			} catch(e) {}		}		return undefined; // not found yet means, there is nothing to find	}} // iffunction checkParameter(condition, message) {	if (!condition) {		if (SHOW_ERRORS) {			alert(message);		}	}	return condition;} // checkParameter/**send an Ajax call to the given URL.httpMethod					string		HTTP request method, for example 'GET' or 'POST'.url									string		url to be called.asynchronous				boolean	should the call be asynchronous?timeout							integer		if this is greater then 0, a timeout guardian will be installed, which cancels the request after the given time in milliseconds.statusOKHandler			function		will be called, if Ajax call is successful.statusErrorHandler			function		(optional) will be called, if Ajax call returns an error.statusTimeoutHandler	function		(optional) will be called, if the timeout limit is reached and the request is cancelled.contentType					string		(optional) content type of the request (must be 'application/x-www-form-urlencoded' for POST requests).requestHeaders				array(n, 2)	(optional) array of more request headers; for each header it should contain an array(2) the the name and the value of the request header to be added.postArguments				string		(optional, but mandatory for POST requests) the parameters fo the POST request ('name=value' pairs divided by '&') */function callServer(httpMethod, url, asynchronous, timeout, statusOKHandler, statusErrorHandler, statusTimeoutHandler, contentType, requestHeaders, postArguments) {	// always a good idea to check the parameters	if (!checkParameter(httpMethod, 'The parameter "httpMethod" must not be empty.')) return false;	if (!checkParameter(url, 'The parameter "url" must not be empty.')) return false;	if (!checkParameter(asynchronous, 'The parameter "asynchronous" must not be empty.')) return false;  // how to check a boolean?	if (!checkParameter(statusOKHandler, 'The parameter "statusOKHandler" must not be empty.')) return false;	if (!checkParameter(postArguments || httpMethod != 'POST', 'The parameter "postArguments" must not be empty for POST requests.')) return false;	var request = new XMLHttpRequest();	var timeoutGuardian = undefined;	var timedOut = false;		function handleStateChange() {		switch (request.readyState) {			case 0 : // UNINITIALIZED				break;			case 1 : // LOADING				break;			case 2 : // LOADED				break;			case 3 : // INTERACTIVE				break;			case 4 : // COMPLETED				handleStatusCompleted();				break;			default : // invalid status ?!				if (SHOW_ERRORS) {					alert('The XMLHttpRequest has reached an invalid status:' + request.readyState);				}		}	} // callServer.handleStateChange	function isRequestInProcess() {		return (request != null && request.readyState >= 1 && request.readyState <= 3);	} // callServer.isRequestInProcess	function processTimeout() {		if (request != null && isRequestInProcess()) { // only if request is still being processed			timedOut = true;			request.abort(); // cancel it			if (statusTimeoutHandler) { // call custom timeout handler, if given				statusTimeoutHandler(request, timeout, url);			} else { // or a generic one else				defaultStatusTimeoutHandler(request, timeout, url);			}		}	} // callServer.processTimeout	function handleStatusCompleted() {		// if the request timed out, it was apparently not successful		if (timedOut) {			return false;		}				// if a timeout guardian has been installed, it will be stopped now.		if (timeoutGuardian && isRequestInProcess()) {			window.clearTimeout(timeoutGuardian)		}				var result = (request.status == 200 || request.status == 304); // 200 is 'OK' and 304 is 'OK, not modified'		if (result) { // OK			statusOKHandler(request);		} else { // everything else is a (kind of) error			if (statusErrorHandler) { // call custom timeout handler, if given				statusErrorHandler(request,  url);			} else { // or a generic one else				defaultStatusErrorHandler(request, url);			}		}		request = null; // deallocate the request		return result;	} // callServer.handleStatusCompleted	if (request) {		// 'opens' the request		request.open(httpMethod, url, asynchronous);		// register callback handler if request is asynchrous		if (asynchronous && statusOKHandler) {			request.onreadystatechange = handleStateChange;		}			// set content type		if (contentType) {			request.setRequestHeader('Content-Type', contentType);		} else if (httpMethod == 'POST') { // this content type must be set on POST request			request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');		}		// append additional request headers		if (requestHeaders) {			for (var i = 0; i < requestHeaders.length; ++i) {				request.setRequestHeader(requestHeaders[i][0], requestHeaders[i][1]);			}		}				// install timeout guardian if appropriate		if (asynchronous && timeout > 0) {			timeoutGuardian = window.setTimeout(processTimeout, timeout);		}		// send the request		if (postArguments) {			request.send(postArguments);		} else {			request.send(null);		}		// care for handling the results of synchronous calls		if (!asynchronous) {			return handleStatusCompleted();		}	}	return true; // everything has gone fine, if we reached this point} // callServerfunction defaultStatusErrorHandler(request, url) {	// check parameters	if (!checkParameter(request, 'The parameter "request" must not be empty.')) return;	if (SHOW_ERRORS) {		alert('An error has occured while processing this XMLHttpRequest:\n\tError code:\t' + request.status + '\n\tError text:\t' + request.statusText + (url ? '\n\tURL:\t' + url : ''));	}} // defaultStatusErrorHandlerfunction defaultStatusTimeoutHandler(request, timeout, url) {	// check parameters	if (!checkParameter(request, 'The parameter "request" must not be empty.')) return;	if (!checkParameter(request, 'The parameter "timeout" must not be empty.')) return;					if (SHOW_ERRORS) {		alert('The XMLHttpRequest was cancelled after ' + timeout + ' milliseconds:'+ (url ? '\n\tURL:\t' + url : ''));		// There seems to be an issue with the Mozilla Firefox (1.5.0.1 de):		// The alert is shown after the server has responded and throws an exception:		// Error: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  		// location: "JS frame :: http://localhost/ajax/EC-Demo.nsf/ajax-utils.js :: handleStatusCompleted :: line 134"  data: no]Quelldatei: http://localhost/ajax/EC-Demo.nsf/ajax-utils.jsZeile: 134	}} // defaultStatusTimeoutHandlerfunction createSetFieldValueHandler(id) {	// check parameters	if (!checkParameter(id, 'The parameter "id" must not be empty.')) return undefined;	var field = $(id);	if (field && field.value) { // if the field exists and has a 'value' attribute		// create a new function and return it.		// replace(/\n$/, '') deletes an CR at the end of the result.		// LotusScript agents append CR automatically and this confuses Opera.		return new  Function('request', '$("' + id + '").value = (request.responseText.replace(/\\n$/, \'\'));');	} else {		if (SHOW_ERRORS) {			alert('There is no element with the given id "' + id + '" or it is missing a "value" attribute.');		}	}} // createSetFieldValueHandlerfunction createCallFunctionWithTextHandler(functionName) {	// check parameters	if (!checkParameter(functionName, 'The parameter "functionName" must not be empty.')) return undefined;	// create a new function and return it.	return  new  Function('request', functionName + '(request.responseText);');} // createCallFunctionWithTextHandlerfunction createCallFunctionWithXMLHandler(functionName) {	// check parameters	if (!checkParameter(functionName, 'The parameter "functionName" must not be empty.')) return undefined;	// create a new function and return it.		return  new  Function('request', functionName + '(request.responseXML);');} // createCallFunctionWithXMLHandler/*********************************************** * DbColumn and DbLookup functions   * Added - July 10, 2009 ************************************************/ var req;var attrvar xmlkey;var resultColXML= new Array()var resultlkpXML= new Array()var ObjCombo1;var ObjCombo2;var lkpKey;/*--------------------------- Dbcolumn function start here server						string		URL of the server eg "http://10.77.4.222"path						string		relative path to the database from the Data directory eg "OtherDevelopment/PAAS/PAASAdmin.nsf"view						string		name of the view to call.   The view must be sorted and unique as we do not check for uniquenesscolumn					integer	the column of the view you want to returnSubject					object		this is the field object you want to imput the lookup into  eg document.forms[0].Field1-------------------*/function dbColumn(server,path,view,column,Subject,isAsync) {	ObjCombo1=document.getElementById(Subject)   //Use ObjCombo1 as it is global and can then be referenced by the XML return function.	var pos=0;	currURL = (document.location.href).toLowerCase(); // clean up the servername passed by the caller	if (trim(server) == "")  	{		pos = currURL.indexOf('://'); 		if (pos < 0 ) server = "http://"+window.location.host 		else  		{			pos += 3;			pos = currURL.indexOf('/', pos);			server = currURL.substring(0, pos)		}   	}// clean up the path that was passed by the caller	if( trim(path) == "" )  	{		if( pos > 0 )   		{			newPos = currURL.indexOf('.nsf',pos);    			if (newPos > 0)			{				path = currURL.substring(pos+1,newPos+4)			}		}	}// ensure that the column number is a valid number, if not set this to column #1	if( !isNaN(column) ) column -= 1; // Build the URL and add the ?Readviewentries to the end to get the response back in XML  	vurl = trim(server)+"/"+trim(path)+"/"+view+"?Readviewentries"	callServer('GET', vurl, isAsync, 5000, createCallFunctionWithXMLHandler('dbColPopulate'))	}/* Function used to extract value one by one from XML file returned by the DbColumn call */function dbColPopulate(response){// Parse the XML response to build a list of values to put into the DbColumn requested field	NodeList = response.getElementsByTagName("viewentry") 	for (var k=0;k<NodeList.length;k+=1)	{		child = response.getElementsByTagName('text')[k].firstChild 		while (child != null)		{ 			filterNode = response.getElementsByTagName("viewentry") 			var filterItem = filterNode.item(k); 			posNumber = filterItem.getAttribute("position");      			if (( child.nodeType == 3) && (posNumber.indexOf(".")==-1)) 			{  				resultColXML[k] = trim(child.nodeValue);			} 			child = child.nextSibling 		}   	}	var finalresult= new Array()	var tmpstr="";	var sep="";	for (var p=0;p<resultColXML.length;p++)	{		if (resultColXML[p] != '' && resultColXML[p] != null )		{			tmpstr =tmpstr+sep+trim(resultColXML[p])			sep="#"		} 	}	finalresult = tmpstr.split("#")	writeInCombo(finalresult,ObjCombo1)	// set the style to visible if it was previously set to hidden  	setStyle(ObjCombo1.id, 'visibility', 'visible');}/*--------------------------- Dblookup function start hereserver						string		URL of the server eg "http://10.77.4.222"path						string		relative path to the database from the Data directory eg "OtherDevelopment/PAAS/PAASAdmin.nsf"view						string		name of the view to call.   The view must be categorized so we can look for the key in the first columnkey						string		what is the unique identifier we are looking forcolumn					integer	the column of the view you want to returnSubject					object		this is the field object you want to imput the lookup into  eg document.forms[0].Field2 -------------------*/function dbLookup(server,path,view,key,column,Name,isAsync,luType){	lkpKey=key													// the return XML function requires this key to sort the responses and only take the items we want.	ObjCombo2=document.getElementById(Name)  	//Use ObjCombo2 as it is global and can then be referenced by the XML return function.	var pos=0;	currURL = (document.location.href).toLowerCase();// clean up the servername passed by the caller	if (trim(server) == "")	{		pos = currURL.indexOf('://'); 		if (pos < 0 ) server = "http://"+window.location.host 		else		{			pos += 3;			pos = currURL.indexOf('/', pos);			server = currURL.substring(0, pos)		}	}// clean up the pathname passed by the caller	if( trim(path) == "" )	{		if( pos > 0 )		{			newPos = currURL.indexOf('.nsf',pos);			if (newPos > 0)			{				path = currURL.substring(pos+1,newPos+4)			}		}	}// ensure that the column number is a valid number, if not set this to column #1	if( isNaN(column) ) {		viewColumn = 0;	} else {		viewColumn = column-1;	} // Build the URL and add the ?Readviewentries to the end to get the response back in XML  	vurl = trim(server)+"/"+trim(path)+"/"+view+"?Readviewentries&restricttocategory="+lkpKey	if (luType == undefined) {		lookupType = 'select';	} else {		lookupType = 'list';	}//alert(vurl)	callServer('GET', vurl, isAsync, 5000, createCallFunctionWithXMLHandler('dbLupPopulate'))	}/* Function used to extract value one by one from XML file returned by the DbColumn call *//* Function used to check whether XML file loaded completely or not */function dbLupPopulate(responseXML){// Parse the XML response to build a list of values to put into the DbLookup requested field	NodeList = responseXML.getElementsByTagName("viewentry") 	var tmplkpstr="";	var sep="";     	for(var i=0; i<NodeList.length; i++)	{		tmplkpstr = tmplkpstr+sep+NodeList[i].getElementsByTagName("text")[viewColumn].childNodes[0].nodeValue// 2009-08-17 rw - added the view column number.   Somehow it was hardcoded???//		tmplkpstr = tmplkpstr+sep+NodeList[i].getElementsByTagName("text")[0].childNodes[0].nodeValue		sep="#"	} 	if (lookupType == 'list') {		setText(ObjCombo2.name, tmplkpstr)//		ObjCombo2.text = tmplkpstr;	} else {		finallkpresult = tmplkpstr.split("#")		writeInCombo(finallkpresult,ObjCombo2)		// set the style to visible if it was previously set to hidden	  	setStyle(ObjCombo2.id, 'visibility', 'visible');	}	}/*--------------------------- writing in combo function start heredata						string		the final results of the XML parsing - the data you want in you listfldCombo					string		the object of the field that was originally requested -------------------*/function writeInCombo(data,fldCombo){	fldCombo.length=0	fldCombo.length +=1	fldCombo[fldCombo.length-1].text = "--Select--"	for(iCount=0;iCount<data.length;iCount++)	{		fldCombo.length +=1		strText=data[iCount]  		if (strText !=undefined && strText != null)		{ 			fldCombo[fldCombo.length-1].text = trim(strText) 		}	} }// 2009-07-16 pb, added jsLookup function to return server values to a js array// no async parameter as it must be a synchronous callbackfunction jsLookup(server,path,view,key,column){try{	lkpKey=key	// the return XML function requires this key to sort the responses and only take the items we want.	var pos=0;	currURL = (document.location.href).toLowerCase();// clean up the servername passed by the caller	if (trim(server) == "")	{		pos = currURL.indexOf('://'); 		if (pos < 0 ) server = "http://"+window.location.host 		else		{			pos += 3;			pos = currURL.indexOf('/', pos);			server = currURL.substring(0, pos)		}	}// clean up the pathname passed by the caller	if( trim(path) == "" )	{		if( pos > 0 )		{			newPos = currURL.indexOf('.nsf',pos);			if (newPos > 0)			{				path = currURL.substring(pos+1,newPos+4)			}		}	}// ensure that the column number is a valid number, if not set this to column #1	if( !isNaN(column) ) column -= 1; // Build the URL and add the ?Readviewentries to the end to get the response back in XML  	vurl = trim(server)+"/"+trim(path)+"/"+view+"?Readviewentries&restricttocategory="+lkpKey	callServer('GET', vurl, 'false', 5000, createCallFunctionWithXMLHandler('jsLuPopulate'))	return globalArray; // from jsLuPopulate	}	catch(e)	{		alert('catch detected in jsLookup: ' + e.message);	}	}/* Function used to extract value one by one from XML file returned by the DbColumn call *//* Function used to check whether XML file loaded completely or not */function jsLuPopulate(responseXML){try{// Parse the XML response to build a list of values to put into the DbLookup requested field	NodeList = responseXML.getElementsByTagName("viewentry") 	var tmplkpstr="";	var sep="";	for(var i=0; i<NodeList.length; i++)	{		tmplkpstr = tmplkpstr+sep+NodeList[i].getElementsByTagName("text")[0].childNodes[0].nodeValue		sep="\u00A5"	} // 2009-08-12 - rw//	globalArray = makeArray(tmplkpstr.split("\u00A5")); // in jsUI	globalArray = tmplkpstr.split("\u00A5");	return;		}	catch(e)	{		alert('catch detected in jsLuPopulate: ' + e.message);	}	}
