/*
 * © by the Inghuimische.de team (webmaster at inghuimische.de)
 *
 * If you want to copy or use the code in any way, please ask for permission.
 */

var HTTP_REQUEST_TIMEOUT= 10* 1000;

// the properties of this object are automatically persisted through page reload
var persistentValues= new Object();

// this object contains all cookie properties
var cookies= new Object();

// the functions to execute on page load
var initFunctions= new Array();

// the functions to execute before leaving a page
var destroyFunctions= new Array();

// some browser-checks
navigator.appVersion.match(/MSIE (\d).\d+/);
var isIE6= document.all&& RegExp.$1< 7;
var isIE7= RegExp.$1>= 7;

// set the event-handlers
window.onload= load;
window.onunload= unload;

// ??
var snow= new Array();

// loading an additional java-script file
function loadLib( lib){
	document.writeln('<script src="'+ lib+ '" type="text/javascript"></script>');
}

// a new page was loaded
function load(){
	// first try to restore the peristentValues
	var pairs= self.name.split( ";");	
	for( var i= 0; i< pairs.length; i++) {
		var pair= pairs[ i].split( "=", 2);
		if( pair[ 1]&& pair[ 1].match( /^true|false|\d+$/))
			persistentValues[ pair[ 0]]= eval( String(pair[ 1]));
		else
			persistentValues[ pair[ 0]]= decodeURIComponent( pair[ 1]);
	}

	// then split the cookie into the diffrent properties
	pairs= document.cookie.split(";");	
	for( var i= 0; i< pairs.length; i++) {
		var pair= pairs[i].split("=", 2);
		cookies[ pair[0].replace(/^\s+/, "")]= pair[ 1];
	}

	// and call all initialation functions
	for( var i= 0; i< initFunctions.length; i++)
		initFunctions[ i]();
}

// unload the current page
function unload(){
	// execute the installed destruction-functions
	for( var i= 0; i< destroyFunctions.length; i++)
		destroyFunctions[ i]();
		
	// try to persist the persistentValues
	self.name= "";
	for( var property in persistentValues)
		self.name+= property+ "="+ encodeURIComponent( persistentValues[ property])+ ";";
}

// create a new HTML-element of the specified typ(e) and the eventually set it's parent and type
function createElement( typ, parent, type){
	var element= document.createElement( typ);
	element.appendTextNode= function( text) {
		this.appendChild( document.createTextNode( text));
	}
	if( type)
		element.type= type;
	if( parent)
		parent.appendChild( element);
	return element;
}

// create a new XML-document
function createXMLDocument(){
	var doc;
	if( window.ActiveXObject) {
		doc= new ActiveXObject("Microsoft.XMLDOM");
		doc.async= "false";
	}else
		doc= document.implementation.createDocument("", "", null);
	return doc;
}

// render debug-messages into the page
var debugDiv;
function debug( msg){
	if(!debugDiv){
		debugDiv= createElement( "div", document.getElementsByTagName("body")[0]);
		debugDiv.style.position= "absolute";
		debugDiv.style.top= "0px";
		debugDiv.style.right= "0px",
		debugDiv.style.width= "300px";
		debugDiv.style.backgroundColor= "#aaaaaa";
		debugDiv.style.zIndex= 999;
		debugDiv.style.opacity= 0.6;
		debugDiv.style.fontFamily= "Arial";
		debugDiv.style.fontSize= "0.6em";
		debugDiv.style.padding= "3px";
		debugDiv.innerHTML= "<p><b>Debug:</b></p>";
	}
	var div= createElement("div", debugDiv);
	div.innerHTML= msg;
}

function createXMLHttpRequest() {
	try {
		return new ActiveXObject("Msxml2.XMLHTTP");
	} catch( ex) {}
	try {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} catch( ex) {}
	return new XMLHttpRequest();
}

// constructor for an new ServerCallContext on javascript side
// (servletURL ist the URL of the ServerCallServlet including the correct target)
function ServerCallContext( servletURL){
	var httpRequest= createXMLHttpRequest();
	
	// this function calls the method on server-side and passes all additional arguments
	this.call= function( methodName){
		// is this httpRequest-object ready to use?	
		if( httpRequest.readyState!== 0&& httpRequest.readyState!== 4)
			return;
		
		try{
			// build up the httpRequest-XML-document
			var messageDoc= createXMLDocument();
			var rootElement= messageDoc.appendChild( 
				messageDoc.createElement( "request"));
			rootElement.setAttribute( "selfmade", "false");
			var methodElement= rootElement.appendChild( 
				messageDoc.createElement( "method"));
			methodElement.setAttribute( "name", methodName);
			
			// add the parameters
			for( var i= 1; i< arguments.length; i++)
				methodElement.appendChild(
					messageDoc.createElement( "param"))
					.appendChild( messageDoc.createTextNode( arguments[ i]));
		} catch( ex){
			// for Opera we try to build up the XML ourselves
			var messageDoc= '<request selfmade="true"><method name="'+ methodName+ '">';
			for( var i= 1; i< arguments.length; i++)
				messageDoc+= "<param>"+	arguments[ i]+ "</param>";
			messageDoc+= '</method></request>';
		}
		
		var self= this;
		
		var requestTimeout = setTimeout(function() {
			httpRequest.onreadystatechange= null;
			httpRequest.abort();
			self.timeout();
	    }, HTTP_REQUEST_TIMEOUT);
	
		// this method is called when the state of the pending httpRequest changes
		httpRequest.onreadystatechange= function(){
			// has the request completed?
			if( httpRequest.readyState!== 4)
				return;
			
			clearTimeout( requestTimeout);

			try{			
				// was the request successfull?
				if( httpRequest.status!== 200) {
					// no, so we've to call the error-handler
					self.error( httpRequest.statusText+ " "+ httpRequest.status);
					return;
				}
			} catch( ex) {
				// Only Mozilla??
				return;
			}

			// pass the response to the handler
			try{
				self.processResponse( httpRequest.responseXML.getElementsByTagName("response")[0]);
			} finally {
				if( isIE6|| isIE7)
					httpRequest.abort();
			}
		}
		
		// prepare and send the request
		httpRequest.open( "POST", servletURL, true);
		httpRequest.setRequestHeader('Content-Type','text/xml; charset=UTF-8');
		httpRequest.send( messageDoc);
	}
}

// defines the default error-handler
ServerCallContext.prototype.error= function( text){
	alert( "Es ist ein Fehler aufgetreten:\n"+ text+ "\n\nEvtl. hilft ein Neuladen der Seite!");
}

ServerCallContext.prototype.timeout= function(){
	alert( "HTTP-request timeout!");
}

// defines the default response-handler
ServerCallContext.prototype.processResponse= function( response){
	alert( "Response not handeled.");
}

// forward the browser to url
function gotoURL( url){
	window.location.href = url;
}

