/*------------------------------------------------------------------------------------
	CF-Javascript Library
	Core-Components
	for ajax-support
------------------------------------------------------------------------------------*/

function cfApplication() {
	this.version = "0.2";
	this.releasedate = "";
	this.components = [];
	window.CF = this;


	/* subclasses */
	
	/* the current window */
	this.window = null;

	/* the current document */
	this.document = null;

	/* information about the requested URL */
	this.request = null;

	/* language information */
	this.language = null;

	/* cookie support */
	this.cookie = null;

	/* useful functions */
	this.fkt =  {};
}

var p = cfApplication.prototype;


p.debugMsg = function(msg) {
	CF.document.document.writeln('<b>debug:</b> '+msg+'<br />');
};

p.versionInfo = function() {
	alert("version: "+this.version);
};

p.registerComponent = function(component) {
    var id = this.components.length;
    this.components[id] = component;
    return id;
};



p.registerPrototype = function(childClass,parentClass) {
    var c = window[childClass];
    var p = window[parentClass];
    if (!c || !p) return alert('Error: cant set prototype "'+parentClass+'" of "'+childClass+'"');
    c.prototype = new p();
    c.prototype._className = childClass;
    c.prototype._pClassName = parentClass;
    return c.prototype;
};




new cfApplication();



/*------------------------------------------------------------------------------------*/
function cfNotifier(parent) {
	this.parent = parent;
	this.items  = new Array();
}

var p = cfNotifier.prototype;


p.find = function (listener, handler, event){
	for (var i in this.items) {
		var item = this.items[i];
		if ((item.listener==listener) && (!handler || (item.handler==handler)) && (!event || (item.event==event)))
			return item;
	}
}



p.add = function (listener, handler, event, window){
	if (!this.find(listener,handler,event))
		this.items[this.items.length] = new cfNotifyObject(this.items.length,this.parent, listener, handler, event, window);
}

p.remove = function (listener, event){
	var newItems = new Array();
	for (var i in this.items) {
		var item = this.items[i];
		if (!((item.listener==listener) && (!event || (item.event==event))))
			newItems[newItems.length] = item;
	}
	this.items = newItems;
}

p.notify = function (event, params){
	var result = '';
	for (var i in this.items) {
		if (this.items[i].event == event) {
			this.items[i].listener [this.items[i].handler](this.parent, event, params);
		}
	}
}

/*--------------------------------------------------*/
function cfNotifyObject(index, parent, listener, handler, event, window) {
	this.index = index;
	this.parent = parent;
	this.listener = listener;
	this.handler= handler;
	this.event = event;
	this.window = window;
}




 


/*------------------------------------------------------------------------------------*/
function cfComponent() {
 	this.id = CF.registerComponent(this);
	this.notifier = null;
};

var p = cfComponent.prototype;

p.addListener = function(listener,handler,event,window) {
	if (!this.notifier)
		this.notifier = new cfNotifier(this);
	this.notifier.add(listener,handler,event,window);
};

p.removeListener = function(listener,handler,event) {
	if (this.notifier)
		this.notifier.remove(listener,handler,event);
};

p.notify = function(event,params) {
	if (this.notifier)
		this.notifier.notify(event,params);
};

p.getReference = function() {
	return 'CF.components['+this.id+']';
};





/*------------------------------------------------------------------------------------*/
function cfWindow() {
   this.cfComponent = cfComponent;
   this.cfComponent();
	this.window = window;
	this.init();
}


p = CF.registerPrototype('cfWindow','cfComponent');


p.init = function () {
	/*
	var self = this;
	this.window.onload = function(event) { self.onLoad(event); };
	*/
}

p.onLoad = function (event) {
	this.notify('loaded',event);
}

p.reload = function () {
	this.window.location.reload();
}



p.reloadUrl = function () {
	/* reload without postvars */
	this.window.location.href = this.window.location.href;
}




p.redirect = function (url) {
	this.window.location.href = url;
}


p.goto = function (url) {
	this.window.location.href = url;
}

CF.window = new cfWindow();








/*------------------------------------------------------------------------------------*/
function cfDocument() {
	this.cfComponent = cfComponent;
	this.cfComponent();
	this.document = window.document;
	this.init();
}


p = CF.registerPrototype('cfDocument','cfComponent');


p.init = function () {
	/*
	var self = this;
	this.document.onmousedown = function(event) { self.onMouseDown(event); };
	this.document.onmouseup = function(event) { self.onMouseUp(event); };
	this.document.onmousemove = function(event) { self.onMouseMove(event); };
	*/
}

p.onMouseDown = function (event) {
	this.notify('mousedown',event);
}

p.onMouseUp = function (event) {
	this.notify('mouseup',event);
}

p.onMouseMove = function (event) {
	this.notify('mousemove',event);
}







CF.document = new cfDocument();






/*------------------------------------------------------------------------------------*/
CF.fkt.True = function() {return true;};
CF.fkt.Talse = function() {return false;};
CF.fkt.Null = function() {};
CF.fkt.Undefinded = function() {return 'undefined';};
CF.fkt.Zero = function() {return 0;};



CF.fkt.alertArray = function(elem) {
	var props = CF.fkt.getElemProperties(elem,true);
	var aStr = '';
	for (var i in props)
		aStr = (aStr)?aStr+'\n'+i+'='+props[i]:i+'='+props[i];
	alert(aStr);
};

CF.fkt.printArray = function(elem) {
	var props = CF.fkt.getElemProperties(elem,true);
	for (var i in props)
		CF.document.document.write(i+'='+props[i]+'<br />');
};


CF.fkt.getElemProperties = function(elem) {
	var result = [];
	for (var i in elem) {
		if (typeof elem[i]=='function')	
			result[i] = '[funktion]';
		else if (typeof elem[i]=='object')	
			result[i] = '[object]';
		else
			result[i] = elem[i];
	}
	return result;
};


CF.fkt.htmlentities = function(text) {
	var text = text.replace(/&auml;/,"ä");
	text = text.replace(/&uuml;/,"ü");
	text = text.replace(/&ouml;/,"ö");
	text = text.replace(/&Auml;/,"Ä„");
	text = text.replace(/&Uuml;/,"Ü");
	text = text.replace(/&Ouml;/,"Ö");
	text = text.replace(/&szlig;/,"ß");
	return text;
}


CF.fkt.getElementById = function(id,aParent) {
	var aParent=(aParent)?aParent:CF.document.document;
	var result = aParent.getElementById(id);
	return result;
};


CF.fkt.getElementsByName = function(aName,aParent) {
	var aParent=(aParent)?aParent:CF.document.document;
	var result = aParent.getElementsByName(aName);
	return result;
};

CF.fkt.getElementsByTagName = function(aName,aParent) {
	var aParent=(aParent)?aParent:CF.document.document;
	var result = aParent.getElementsByTagName(aName);
	return result;
};

CF.fkt.ltrim = function (value) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

CF.fkt.rtrim = function (value) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

CF.fkt.trim = function (value) {
	return CF.fkt.ltrim(CF.fkt.rtrim(value));
}



/*---------------------------------------------------------*/
function cfHttpRequest(method) {
	this.cfComponent = cfComponent;
	this.cfComponent();
	
	
	this.complete = false;
	this.async_mode = true;
	this.method = (method)?method:"GET";
	this.transport = null;
	this.timeout = 10; // seconds
	
	this.postVars = new cfHttpParameters();
	this.getVars = new cfHttpParameters();
	
	
	this.mimeType = "text/plain";
	this.charset = "charset=iso-8859-1";
	
	this.eventnames = [
       "uninitialized",
       "loading",
       "loaded",
       "interactive",
       "complete"
    ];

	
	this.url = null;

}

p = CF.registerPrototype('cfHttpRequest','cfComponent');


p.request = function ( url ) {

	if (!this.transport)
		this.transport = this.createTransport();
	else
		this.transport.abort();

		
		
	if (!this.transport) {
		alert("ERROR: your browser doesn't support http-requests.");
		return;
	}
		
	
	this.complete = false;
		
	url = (url)?url:this.url;
	if (!url) 
		return;
	
	var getParams = this.getVars.getParamStr();

	if (getParams)
		url += '?'+getParams;

	this.transport.open(this.method, url, this.async_mode);

	var self = this; // de-reference to self

	if ( this.async_mode ) {
		this.transport.onreadystatechange = function () { self.transportStateChange(); };
		setTimeout(function() { self.transportStateChange(-1) },this.timeout);
	}

	this.setRequestHeaders();

	if ( this.method == "POST" ) {
		var postParams = this.postVars.getParamStr();
		this.transport.setRequestHeader("Content-length", postParams.length);
		this.transport.setRequestHeader("Connection", "close");		
		this.transport.send(postParams);
	} else {
      	this.transport.send(null);
   }
};

p.setRequestHeaders = function () {

	this.transport.setRequestHeader( "Requested-With", "cfHttpRequest" );
	if ( this.method == "POST" ) {
		this.transport.setRequestHeader("Content-type", "application/x-www-form-urlencoded; " + this.getCharset());
	} else {
		this.transport.setRequestHeader("Content-type", this.getMimeType() + "; " + this.getCharset() );
	}
	
	if (this.transport.overrideMimeType) {
		this.transport.overrideMimeType(this.getMimeType() + "; " + this.getCharset());
		this.transport.setRequestHeader( "Connection", "close" );
	}
}

p.getMimeType = function () {
	return this.mimeType;
}

p.getCharset = function () {
	return this.charset;
}

p.isSuccess = function () {
	return this.transport &&
			(this.transport.status == "undefined" || 
            this.transport.status == 0 || 
            (this.transport.status >= 200 && this.transport.status < 300));
}

p.transportStateChange = function () {
	var readyState = this.transport.readyState;
	if (readyState >= 0) {
		var event = this.eventnames[readyState];
		if (!this.complete && (event == "complete")) {
			
			/* prevent receiving the "complete" signal twice !?!? 
			  (yes, the transport does it!)
			*/ 
			this.complete = true;  
			
			/* Avoid memory leak in MSIE: clean up the oncomplete event handler */
			this.transport.onreadystatechange = function () {};
			this.notify('complete',this.transport);
   		} 
	}
};


p.close = function () {
	if (this.transport) {
		delete this.transport;
		this.transport = null;
	}	
};



p.createTransport = function () {
    if ( window.XMLHttpRequest )
        return new window.XMLHttpRequest();

        
    // This tests for ActiveXObject in IE5+
    if ( window.ActiveXObject && window.clipboardData ) {
        var msxmls = new Array(
            "Msxml2.XMLHTTP.5.0"
           ,"Msxml2.XMLHTTP.4.0"
           ,"Msxml2.XMLHTTP.3.0"
           ,"Msxml2.XMLHTTP"
           ,"Microsoft.XMLHTTP"
        );
        for ( var i = 0; i < msxmls.length; i++ ) {
            try {
                var result = new ActiveXObject(msxmls[i]);
                return result;
                break;
            }
            catch(e) {
            }
        }
    }
    return null;
};



/*---------------------------------------------------------*/
function cfHttpParameters() {
	this.cfComponent = cfComponent;
	this.cfComponent();
	
	this.items = [];
}


p = CF.registerPrototype('cfHttpParameters','cfComponent');

p.clear = function () {
	this.items = [];
}

p.assign = function (params) {
	for (var i in params) 
		this.set(i,params[i]);
}

p.set = function (name,value) {
	this.items[name] = value;
}

p.get = function (name,alt) {
	if (this.items[name]!=null)
		return this.items[name]
	else
		return alt;
}

p.getParamStr = function () {
	var result = '';
	for (var i in this.items) {
		if (this.items[i]!=null) {
			if (result.length>0)
				result += '&'+i+'='+escape(this.items[i])
			else
				result = i+'='+escape(this.items[i]);
		}
	}
	return result;
}




/*---------------------------------------------------------*/
/*---------------------------------------------------------*/
/*---------------------------------------------------------*/
function cfAjaxRequest(method) {
	this.cfComponent = cfComponent;
	this.cfComponent();
	
	this.httprequest = new cfHttpRequest(method);
	this.httprequest.addListener(this,'HandleResponse','complete');
}

p = CF.registerPrototype('cfAjaxRequest','cfComponent');


p.request = function (url,getParams,postParams) {
	if (getParams) {
		this.httprequest.getVars.clear();
		this.httprequest.getVars.assign(getParams);
	}
	if (postParams) {
		this.httprequest.postVars.clear();
		this.httprequest.postVars.assign(postParams);
	}
	this.httprequest.request(url);
}


p.HandleResponse = function (sender, event, response) {
	// to override;
}


/*---------------------------------------------------------*/
function cfJsonAjax(method) {
	this.cfAjaxRequest = cfAjaxRequest;
	this.cfAjaxRequest(method);
	
	this.result = null;
	this.errors = null;
	this.header = null;
	this.data = null;

}


p = CF.registerPrototype('cfJsonAjax','cfAjaxRequest');


p.HandleResponse = function (sender, event, response) {
	var responseText = response.responseText;
	if (responseText) {
		var obj = eval("("+responseText+")");
		this.header = obj['header'];
		this.data = obj['data'];
		this.result = this.header['result'];
		this.errors = this.header['errors'];
		this.notify('dataAvailable');
	}
}



/*---------------------------------------------------------*/
function cfPlainAjax(method) {
	this.cfAjaxRequest = cfAjaxRequest;
	this.cfAjaxRequest(method);
	
	this.responseText = null;
}


p = CF.registerPrototype('cfPlainAjax','cfAjaxRequest');


p.HandleResponse = function (sender, event, response) {
	this.responseText = response.responseText;
	this.notify('dataAvailable',this.responseText);
}




//-----------------------------------------
function cfLayer(aLayer) {
	this.cfComponent = cfComponent;
	this.cfComponent();

	this.layer = null;
	this.style = null;
	this.float = null;
	if (aLayer) {
		if ((typeof aLayer)=='string')
			aLayer = CF.fkt.getElementById(aLayer);
		if (aLayer)
			this.setLayer(aLayer);
	}
}

p = CF.registerPrototype('cfLayer','cfComponent');


p.setLayer = function (aLayer) {
	this.layer = aLayer;
	this.layer.cfLayer = this;
	this.layer.componentid = this.id;
	this.style = this.layer.style;
	this.setStyle('position','absolute');
	this.setVisible(false);
	this.setPosition(0,0);
}

p.createLayer = function (aParent) {
	aParent = (aParent)?aParent:window.CF.document.document.body;
	var newDIV = document.createElement("div");
	var layer = aParent.appendChild(newDIV);
	this.setLayer(layer);
}


p.setStyle = function (aName,aValue) {
	if (!this.layer) {
		this.createLayer();
	}
	if (this.style) {
		this.style[aName] = aValue;
	}
}


p.getStyle = function (aName) {
	if (!this.layer)
		this.createLayer();
	return this.style[aName];
}


p.setPosition = function (l,t) {
	this.setLeft(l);
	this.setTop(t);
}

p.setLeft = function (l) {
	this.setStyle('left',this.fDim(l));
}

p.setTop = function (t) {
	this.setStyle('top',this.fDim(t));
}


p.setSize = function (w,h) {
	this.setWidth(w);
	this.setHeight(h);
}


p.setWidth = function (w) {
	this.setStyle('width',this.fDim(w));
}

p.setHeight = function (h) {
	this.setStyle('height',this.fDim(h));
}


p.fDim = function (dimension,format) {
	if (!dimension)
		dimension = '0';
	format = (format)?format:'px';
	return dimension+format;
}


p.getHtml = function () {
}


p.doBeforeShow = function () {
}

p.doBeforeHide = function () {
}

p.setLayerEvents = function () {
	var _this = this;
	this.layer.onmousedown = function(event) { _this.internalOnMouseDown(event); };
	this.layer.onmouseup = function(event) { _this.internalOnMouseUp(event); };
	this.layer.onmouseover = function(event) { _this.internalOnMouseEnter(event); };
	this.layer.onmouseout = function(event) { _this.internalOnMouseLeave(event); };
}

p.clearLayerEvents = function () {
	this.layer.onmousedown = null;
	this.layer.onmouseup = null;
	this.layer.onmouseover = null;
	this.layer.onmouseout = null;
}


p.onMouseDown = function () {
}

p.onMouseUp = function () {
}

p.onMouseEnter = function () {
}

p.onMouseLeave = function () {
}


p.internalOnMouseDown = function (event) {
	this.notify('mousedown');
	this.onMouseDown(event);
}

p.internalOnMouseUp = function (event) {
	this.notify('mouseup');
	this.onMouseUp(event);
}

p.internalOnMouseEnter = function (event) {
	this.notify('mouseenter');
	this.onMouseEnter(event);
}

p.internalOnMouseLeave = function (event) {
	this.notify('mouseleave');
	this.onMouseLeave(event);
}


p.setVisible = function (state) {
	if (state) {
		if (!this.layer)
			this.createLayer();
		if (html = this.getHtml())
			this.setHTML(html);
		this.setLayerEvents();
		this.doBeforeShow();
	} else {
		this.clearLayerEvents();
		this.doBeforeHide();
	}
	this.setStyle('visibility',(state)?'visible':'hidden');
	if (state)
		this.notify('show');
	else
		this.notify('hide');
		
}

p.show = function (l,t) {
	if (l!=null)
		this.setLeft(l);
	if (t!=null)
		this.setTop(t);
	this.setVisible(true);
}

p.hide = function () {
	this.setVisible(false);
}


p.getVisible = function () {
	return (this.getStyle('visibility')!='hidden');
}



p.setZIndex = function (level) {
	this.setStyle('zIndex',level);
}


p.setHTML = function (html) {
	if (!this.layer)
		this.createLayer();
	this.layer.innerHTML = html;
}



p.setDisplayType = function (aType) {
	this.setStyle('display',aType);
}

p.getDisplayType = function (aType) {
	return this.getStyle('display');
}



p.setFloat = function (state) {
	this.setStyle('position',(state)?'absolute':'relative');
}


p.getFloat = function (state) {
	var state = this.getStyle('position');
	return (state=='absolute')?true:false;
}







/*---------------------------------------------------------*/
function cfDivControl(layer) {
	this.cfComponent = cfComponent;
	this.cfComponent();

	this.layer = null;
	if ((typeof layer) == 'string')
		this.layer = CF.fkt.getElementById(layer)
	else if ((typeof layer) == 'object')
		this.layer = layer;
	
}

p = CF.registerPrototype('cfDivControl','cfComponent');


p.setStyle = function (aName,aValue) {
	this.layer.style[aName] = aValue;
}


p.getStyle = function (aName) {
	return this.layer.style[aName];
}


p.setVisible = function (state) {
	this.setStyle('display',(state)?'block':'none');
}


p.clear = function () {
	this.setHTML('');
}

p.show = function () {
	this.setVisible(true);
}

p.hide = function () {
	this.setVisible(false);
}


p.getVisible = function () {
	return (this.getStyle('display')!='none');
}

p.setHTML = function (html) {
	this.layer.innerHTML = html;
}
