
	window.onload = function() {
		Global.data = GlobalData;
		Global.init();
		MessageHandler.init();
	};


	var Global = {
		data: null,
		onload: new Array(),
		
		
		init: function() {
			this.buildRadio();
			
			Object.keys(FormData).each(function(form) {
				Global.fillForm(FormData[form], form);
			});
			
			Global.onload.each(function(func) {
				eval(func);
			});
			
			this.processSText();
		},
		
		
		call: function(func) {
			Global.onload.push(func);
		},
		
		
		addCSS: function(file) {
			document.write('<style media="all" type="text/css"> @import url("/css/' + file + '");</style>');
		},
		
		
		fillForm: function(data, form) {
			var form = $(document.forms[form]);
			
			if(!form) return;
			
			Object.keys(data).each(function(name) {
				var inp = null;
				var dat = null;
				
				if(typeof data[name] == "object") {
					Object.keys(data[name]).each(function(name2) {				
						if(typeof data[name][name2] == "object") {
							if(data[name][name2] == null) {
								return;
							}
							
							Object.keys(data[name][name2]).each(function(name3) {
								inp = form.select("[name='" + name + "[" + name2 + "][" + name3 + "]']");
								dat = data[name][name2][name3];
								
								inp.each(function(inp) {
									Global.fillInput(inp, dat);
								});
							});
						}
						else {
							inp = form.select("[name='" + name + "[" + name2 + "]']");
							dat = data[name][name2];
							
							inp.each(function(inp) {
								Global.fillInput(inp, dat);
							});
						}						
					});
				}
				else {
					inp = form.select("[name='" + name + "']");
					dat = data[name];
					
					inp.each(function(inp) {
						Global.fillInput(inp, dat);
					});
				}
			});
		},
		
		
		fillInput: function(inp, value) {
			if(inp == null) {
				return;
			}
			
			switch(inp.tagName) {
				case "INPUT":
					switch(inp.type) {
						case "hidden":
						case "password":
						case "text":
							inp.value = value;
							break;
							
						case "checkbox":
						case "radio":								
							if(inp.value == value) {
								inp.checked = true;
								if(inp.onclick) inp.onclick();
								if(inp.onchange) inp.onchange();
							}
							break;
					}
					break;
					
					
				case "SELECT":
					for(var i = 0; i < inp.length; i++) {
						if(inp.options[i].value == value) {
							inp.selectedIndex = i;
							break;
						}
					}
					break;
				
				
				case "TEXTAREA":
					inp.value = value;
					break;
			}
		},
		
		
		buildRadio: function() {
			$$("[radioname]").each(function(img) {
				var id = img.identify();
				var rad = Builder.node("input", {
					id: "radio_" + id,
					type: "radio", name: img.readAttribute("radioname"), 
					value: img.readAttribute("radiovalue"),
					style: "display: none"
				});
				
				img.insert({after: rad});
				img.writeAttribute("checke", "false");
				
				img.observe("click", function(e) {
					$$("[radioname='" + this.readAttribute("radioname") + "']").each(function(img) {
						img.src = "/img/index/checkbox1.gif";
						img.writeAttribute("checke", "false");
					});
					
					switch(this.readAttribute("checke")) {
						case "false":
							$("radio_" + this.id).checked = true;
							this.writeAttribute("checke", "true");
							this.src = "/img/index/checkbox2.gif";
							break;
							
						case "true":
							$("radio_" + this.id).checked = false;
							this.writeAttribute("checke", "false");
							this.src = "/img/index/checkbox1.gif";
							break;
					}
				});
			});
		},
		
		
		processSText: function() {
			$$("[stext]").invoke("observe", "focus", function(e) {
				this.value = "";
				this.setStyle({
					color: "#5D5C61"
				});
			});
		}
	};
	

	
	var MessageHandler = {
		messages: {},
		
		init: function() {
			if(Object.isArray(Global.data.messages)) {
				return;
			}
					
			Object.keys(Global.data.messages).each(function(key) {
				MessageHandler.add(key, Global.data.messages[key]);
			});
			
			this.publish();
		},
		
		
		add: function(key, txt) {			
			this.messages[key] = {
				published: false,
				text: txt
			};
		},
		
		
		get: function(key) {
			return this.messages[key].text;
		},
		
		
		truncate: function() {
			Object.keys(this.messages).each(function(key) {
				this.messages[key].published = true;
			}.bind(this));
		},
		
		
		publish: function() {		
			Object.keys(this.messages).each(function(key) {
				this.msgOut(key);
			}.bind(this));
		},
		
		
		publishFirst: function() {
			Object.keys(this.messages).each(function(key) {
				var pub = this.msgOut(key);
				
				if(pub == true) {
					throw $break;
				}
			}.bind(this));
			
			this.truncate();
		},
		
		
		msgOut: function(key) {
			var msg = this.messages[key];
			
			if(msg.published == true) {
				return false;
			}
			
			this.buildMessageWindow(msg);
			msg.published = true;
			
			return true;
		},
		
		buildMessageWindow: function(msg) {
			var div = Builder.node("div", {className: "message", style: "display: none;"}, [
				Builder.node("div", {className: "text"}).update(msg.text),
				Builder.node("div", {className: "options"},[
					Builder.node("input", {type: "button", value: "OK", className: "error_button"}).observe("click", MessageHandler.windowClose)
				])
			]);
			
			
			document.body.appendChild(div);
			
			
			var view = document.viewport.getDimensions();
			var scroll = document.viewport.getScrollOffsets();
			var win = div.getDimensions();

			div.setStyle({
				left: ((view.width / 2) - (win.width / 2)) + "px",
				top: ((view.height / 2) - (win.height / 2)) + scroll.top + "px"
			});

			div.appear({duration: 0.3});
		},
		
		
		windowClose: function(e) {
			this.up(".message").remove();
		}
	};
	
	
	function Confirm(txt, func1, func2) {
		this.func1 = func1;
		this.func2 = func2;
		
		this.div = Builder.node("div", {className: "Confirm"}, [
			Builder.node("div", {className: "handle"}, [
				Builder.node("div", {className: "close"}, "X")	
			]),
			Builder.node("div", [
				Builder.node("div", {className: "text"}, txt),
				Builder.node("input", {type: "button", className: "button true", value: "Ja"}),
				Builder.node("input", {type: "button", className: "button false", value: "Nein"})
			])
		]);
		
		var dim = document.viewport.getDimensions();
		var scl = document.viewport.getScrollOffsets();
		
		this.div.setStyle({
			top: (dim.height / 2) + scl.top + "px",
			left: (dim.width / 2) + scl.left - 150 + "px",
			opacity: 0
		});
		
		document.body.insert(this.div);
		this.div.appear({duration: 0.2});
		
		new Draggable(this.div, {handle: "handle"});
		
		
		this.div.select(".close")[0].onclick = this.close.bind(this);
		this.div.select(".false")[0].onclick = this.noexecute.bind(this);
		this.div.select(".true")[0].onclick = this.execute.bind(this);
	}
		
	Confirm.prototype.close = function() {
		this.div.remove();
	};
		
	Confirm.prototype.execute = function() {
		this.func1();
		this.close();
	};
	
	Confirm.prototype.noexecute = function() {
		if(typeof this.func2 != "undefined") {
			this.func2();
		}
		
		this.close();
	};
	
	
	function clone(obj){
	    if(obj == null || typeof(obj) != 'object')
	        return obj;

	    var temp = new obj.constructor(); // changed (twice)
	    for(var key in obj)
	        temp[key] = clone(obj[key]);

	    return temp;
	}
	
	
	String.prototype.toDate = function() {
		var tmp = this.split("-");
		return new Date(tmp[0], tmp[1] - 1, tmp[2]);
	};
	
	
	String.prototype.toDateWithFormat = function(format) {
		var i = 0;
		var date = new Date();
		
		format.toArray().each(function(f) {
			var tmp = "";
			while($R(0,9).include(this[i])) {
				tmp += this[i++];
			}
			
			switch(f) {
				case "H":
					date.setHours(tmp);
					break;
					
				case "i":
					date.setMinutes(tmp);
					break;
					
				case "d":
					date.setDate(tmp);
					break;
					
				case "m":
					date.setMonth(tmp - 1);
					break;
					
				case "Y":
					date.setFullYear(tmp);
					break;
					
				default:
					i++;
			}
		}.bind(this));
		
		return date;
	};
	
	
	Date.prototype.format = function(formatString) {
		if(typeof formatString == "undefined") {
			formatString = "Y-m-d";
		}
		
		var str = "";
						
		formatString.toArray().each(function(f) {
			switch(f) {
				case "d":
					var tmp = this.getDate();
					str += tmp < 10 ? "0" + tmp : tmp;
					break;
					
				case "m":
					var tmp = this.getMonth() + 1;
					str += tmp < 10 ? "0" + tmp : tmp;
					break;
					
				case "Y":
					var tmp = this.getFullYear();
					str += tmp < 10 ? "0" + tmp : tmp;
					break;
					
				case "H":
					var tmp = this.getHours();
					str += tmp < 10 ? "0" + tmp : tmp;
					break;
					
				case "i":
					var tmp = this.getMinutes();
					str += tmp < 10 ? "0" + tmp : tmp;
					break;
			
				default:
					str += f;
					break;
			}
		}.bind(this));
		
		return str;
	};
	
	
	Number.prototype.format = function(pre, post) {
		var num = this;
		
		if(typeof post != "undefined") {
			num = num.toFixed(post);
		}
		
		if(typeof pre != "undefined") {
			var str = num.toString();
			
			if(str.length < pre) {
				num = "0".times(pre - str.length) + num;
			}
		}
		
		return num;
	};
	
	
	var FormCheck = {
		responseJSON: {},
			
		test: function(form, url) {
			$(form).identify();			
			var button = $(form.id).select("input[type=submit]");
			
			var loader = new Array();
			for(var i = 0; i < button.length; i++) {
				loader[i] = this.buildLoader(button[i]);
			}
			
			new Ajax.Request(url, {
				parameters: form.serialize(),
				
				onComplete: function(r) {				
					if(!r.responseText.isJSON()) {
						return false;
					}				
				
					var err = r.responseText.evalJSON();
					FormCheck.responseJSON = err;
					
					
					if(err.length == 0) {
						form.submit();
						return true;
					}
					
					
					for(var i = 0; i < button.length; i++) {
						loader[i].replace(button[i]);
					}
					
						
					Object.keys(err).each(function(key) {
						MessageHandler.add(key, err[key]);
					});
					MessageHandler.publishFirst();
				}
			});
		
			return false;
		},
		
		
		buildLoader: function(button) {
			var dim = button.getDimensions();
			var loader = new Element("img", {src: "/img/ajax-loader.gif"});
					
			loader.setStyle({
				marginLeft: (dim.width / 2) - 8 + "px"
			});
			
			button.replace(loader);
			return loader;
		}
	};
	
	
	function uniqid(prefix, more_entropy) {	 
	    if(typeof prefix == 'undefined') {
	        prefix = "";
	    }
	 
	    var retId;
	    var formatSeed = function(seed, reqWidth) {
	        seed = parseInt(seed,10).toString(16); // to hex str
	        if (reqWidth < seed.length) { // so long we split
	            return seed.slice(seed.length - reqWidth);
	        }
	        if (reqWidth > seed.length) { // so short we pad
	            return Array(1 + (reqWidth - seed.length)).join('0')+seed;
	        }
	        return seed;
	    };
	 
	    // BEGIN REDUNDANT
	    if(!this.php_js) {
	        this.php_js = {};
	    }
	    // END REDUNDANT
	    if(!this.php_js.uniqidSeed) { // init seed with big random int
	        this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
	    }
	    this.php_js.uniqidSeed++;
	 
	    retId  = prefix; // start with prefix, add current milliseconds hex string
	    retId += formatSeed(parseInt(new Date().getTime()/1000,10),8);
	    retId += formatSeed(this.php_js.uniqidSeed,5); // add seed hex string
	 
	    if(more_entropy) {
	        // for more entropy we add a float lower to 10
	        retId += (Math.random()*10).toFixed(8).toString();
	    }
	 
	    return retId;
	}
	
