

/**
 * $Id: AjaxConnector.js,v 1.1.2.13 2009/05/04 10:44:40 mboehm Exp $
 */
 
var lnkAjaxConnector = null; 

function AjaxConnector() {

 	this.sHost      = null;
	// save this self
	lnkAjaxConnector = this;
	// global xmlhttprequest object
	this.xmlHttp = false;
	/** save the response function */
	this.objResponseObject = null;
	/** session id */
	this.sSID       = null;

	/** set the host */
	this.setSID = function (sSID) {
		this.sSID = sSID;
	}
	
	/** return the hostname*/
	this.getSID = function () {
		return this.sSID;
	}
	
	
	/** set the host */
	this.setHost = function (sHost) {
		this.sHost = sHost;
	}
	
	/** return the hostname*/
	this.getHost = function () {
		return this.sHost;
	}
	
	
	/**
	 * instantiates a new xmlhttprequest object
	 *
	 * @return xmlhttprequest object or false
	 */
	this.getXMLRequester = function (){
	   var xmlHttp = false;
	   // try to create a new instance of the xmlhttprequest object        
	   try {
	      // Internet Explorer
	      if( window.ActiveXObject ) {
	         for( var i = 5; i; i-- ) {
	            try {
	               // loading of a newer version of msxml dll (msxml3 - msxml5) failed
	               // use fallback solution
	               // old style msxml version independent, deprecated
	               if( i == 2 ) {
	               	xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );    
	               }
	               // try to use the latest msxml dll
	               else {
                 		xmlHttp = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
	               }
	               break;
	            }
	            catch( excNotLoadable ) {                        
	                xmlHttp = false;
	            }
	         }
	      }
	      // Mozilla, Opera und Safari
	      else if( window.XMLHttpRequest ) {
	      	xmlHttp = new XMLHttpRequest();
	      }
	   }
	   // loading of xmlhttp object failed
	   catch( excNotLoadable ) {
	      xmlHttp = false;
	   }
	   return xmlHttp ;
	}
	
	/**
	 * send syncron data to server
	 */
	this.sendSyncron = function (axRequest, mapData) {
		return this.sendRequest (null, axRequest, mapData, false);
	}
	 
	/**
	 * private
	 * sends a http request to server
	 */
	this.sendRequest = function (objResponseObject, axRequest, mapData, isAsSyncron) {
		// save the responsefunction for doit after send
		this.objResponseObject = objResponseObject;
		// previous request not finished yet, abort it before sending a new request
		if( this.xmlHttp && this.xmlHttp.readyState ) {
		    this.xmlHttp.abort( );
		    this.xmlHttp = false;
		}
		    
		// create a new instance of xmlhttprequest object
		// if it fails, return
		if( !this.xmlHttp ) {
		    this.xmlHttp = this.getXMLRequester( );
		    if( !this.xmlHttp )
		        return;
		}
      
      // open the connection
      // is it ssl? handle it!
      var sUrl = document.location.protocol+"//"+this.sHost + "/moxanos/ajax";
      
      // Parameter aufbauen
      sParams = "ttt="+(new Date().getTime()) +"&sid=" + this.sSID + "&cmp="+axRequest.getComponent()+"&msg=" + axRequest.getMethod();
      // prüfe ob weitere params übergeben wurden
		if(mapData!=null)
			sParams += this.getCGIFromMap(mapData);

		// document.write(sUrl);
		// Open connection
      this.xmlHttp.open( "POST", sUrl, isAsSyncron );

      //Send the proper header information along with the request
      this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      this.xmlHttp.setRequestHeader("Content-length", sParams.length);
      this.xmlHttp.setRequestHeader("Connection", "close");

		// check is asyncron 
		// if true : set onload data event-handler
		if(isAsSyncron)	
			this.xmlHttp.onreadystatechange = new Function( "", "lnkAjaxConnector.processResponse()" );
		
		this.xmlHttp.send(sParams);    // param = POST data
		
		// check is asyncron
		if(!isAsSyncron) {
			if(this.xmlHttp && this.xmlHttp.responseXML) {
				var dataNode = this.xmlHttp.responseXML.lastChild;
				//alert(this.xmlHttp.responseText);
				// check is xml-data or textdata
				if(dataNode==null || dataNode.tagName!="d")
					return unescape(this.xmlHttp.responseText).replace(/\+/g, ' ');

				else {
					// create dataobject
					var moxTable = this.createMoxTable(dataNode);
					return moxTable;
				}
			}
		}
			
		
		
	}
	
	/** create from a MoxData-object a cgi-string*/
	this.getCGIFromMap = function (mapData) {
		var sOut = "";
		for(var oneData in mapData.getArray()) {
	      sOut += "&";
			sOut += oneData +"="+ encodeURI(mapData.get(oneData)).replace(/=/g, '%3D');
		}		
		return sOut;
	}
	
	
	/**
	 * process the response data from server
	 * only in assyncron mode
	 * @param intID, Integer, ID of this response
	 */
	this.processResponse = function () {
		// status 0 UNINITIALIZED open() has not been called yet.
		// status 1 LOADING send() has not been called yet.
		// status 2 LOADED send() has been called, headers and status are available.
		// status 3 INTERACTIVE Downloading, responseText holds the partial data.
		// status 4 COMPLETED Finished with all operations.
		switch( this.xmlHttp.readyState ) {
			// uninitialized
			case 0:
			// loading
			case 1:
			// loaded
			case 2:
			// interactive
			case 3:
			    break;
			// complete
			case 4:    
				// check http status
				if( this.xmlHttp.status == 200 ){   // success
					
					//alert(this.xmlHttp.responseText);
					var dataNode = this.xmlHttp.responseXml.lastChild;
					if(dataNode==null || dataNode.tagName!="d"){
						this.objResponseObject.ajaxResponseText(this.xmlHttp.responseText);
					} else {
						// create dataobject
						var moxTable = this.createMoxTable(dataNode);
						// start the responsedata
						if(this.objResponseObject!=null)
							this.objResponseObject.ajaxResponse(moxTable);
					}
				
				}
				// loading not successfull, e.g. page not available
				else {
					if( window.handleAJAXError )
						handleAJAXError(this.xmlHttp, intID );
					else
						alert( "ERROR\n HTTP status = " + this.xmlHttp.status + "\n" + this.xmlHttp.statusText ) ;
				}
	    }
	}
	
	
	/**
	 * Create MoxTable from xml-request
	 */
	this.createMoxTable = function (dataNode) {
		var nTableCount = 0;
		var moxTable = null;
		for(var i=0;i<dataNode.childNodes.length;i++) {
			var nodeChilds = dataNode.childNodes[i];
			// create moxTable when nodename is table
			if(nodeChilds.nodeName == "table")
				moxTable = this.createTable(nodeChilds);
			if(nodeChilds.nodeName == "header")
				nTableCount =  nodeChilds.childNodes[0].firstChild.nodeValue;
				
		}
		
		moxTable.setTableCount(nTableCount);
		return moxTable;
	}
	
	/** create table from xml */
	this.createTable = function (tableNode){
		if(tableNode!=null) {
			var moxTable = new MoxTable();
			// read tr
			for(var i=0;i<tableNode.childNodes.length;i++) {
				//read td
				var nodeTr = tableNode.childNodes[i];
				// prüfe ob es sich um ein element handelt
				if(nodeTr.nodeType==3) continue;
				
				var moxData = new MoxData();
				moxData.setID(nodeTr.getAttributeNode("id").value);
				// add moxdata into the table
				moxTable.add(moxData);
				
				for(var i2=0;i2<nodeTr.childNodes.length;i2++) {
					// get child by index
					var oneTd = nodeTr.childNodes[i2];
					
					// prüfe ob es sich um ein element handelt
				   if(oneTd.nodeType==3) continue;
				
					// set param and value in the moxdata-object
					var sValue = oneTd.firstChild!=null ? oneTd.firstChild.nodeValue : "";
					sValue = sValue.replace(/\+/g, ' ');
					sValue = unescape(sValue);
					moxData.setData(oneTd.getAttributeNode("id").value, sValue);
				}
			}
			
		}
		
		return moxTable;
	}
	
	
 	
 }
 
 