var main = {
	toggle_search: false,
	path:{},
	init: function(){
		this.initNavi();
//		this.initFooter();
	},
	initNavi: function(){
		$("navi").childElements().each(function(e){
			if(!e.hasClassName("navi_spacer") && !e.hasClassName("clearer") && Object.isElement(e.down("ul.subs"))){
//				e.down("ul.subs").setStyle({zIndex:50})
				e.observe("mouseenter",function(){
					e.down("ul.subs").show();
				}.bind(this)).observe("mouseleave",function(){
					e.down("ul.subs").hide();
				});
			}
		}.bind(this));
	},
	print: function(){
		window.print();
	},
	today: "",
	tabs: [],
	initFooter: function(){
		var tab_container = $$("div.footer_tabs")[0];
		if(!Object.isUndefined(tab_container)){
			this.tabs = tab_container.select("div.tab");
			this.tabs.each(function(e,i){
				e.content = tab_container.next("div.footer_tabs_content").select("div.tab_content")[i];
				// yeardays highlight
				e.content.select(".entry .text").each(function(t){
					var yearday = t.readAttribute("yearday");
					if(yearday!=""){
						var regexp = eval("/("+yearday+")/gi");
						t.innerHTML = t.innerHTML.replace(regexp,"<em>$1<\/em>");
					}
				}.bind(this));
				
				e.observe("click",function(){
					this.handleFooterTabs(i);
				}.bind(this));
			}.bind(this));
		}
	},
	handleFooterTabs: function(index){
		this.tabs.each(function(e,i){
			if(index==i){
				e.addClassName("active");
				e.content.show();
			} else {
				e.removeClassName("active");
				e.content.hide();
			}
		}.bind(this));
	},
	ajax: function(settings){
		if(Object.isUndefined(settings.path))
			return false;
		
		var callback = Object.isFunction(settings.onSuccess)?settings.onSuccess:Prototype.emptyFunction;
		var callbackError = Object.isFunction(settings.onError)?settings.onError:Prototype.emptyFunction;
		
		new Ajax.Request(settings.path,{
			parameters:settings.parameters||{},
			onSuccess: function(t){			
				var response = t.responseText;
				if(response.isJSON()){
					response = response.evalJSON();
					if(response.error){
						response.error = response.error.gsub("<br>","\n").gsub("<br />","\n").strip();
						if(Object.isUndefined(settings.abortError))
							alert(response.error);
						callbackError(response);
					} else if(callback){
						callback(response);
					}
				}
			}
		});
	},
	url: function(button){
		if(Prototype.Browser.IE){
			location.href = button.href;
		}
	},
	back: function(){
		history.back();
	},
	checkSearch: function(form){
		var input = form.down("input",1); 
		if(input.className.endsWith("active"))
			return true;
		return false;
	},
	searchInput: function(input){
		input.removeAttribute("onclick");
		input.defaultValue = input.value;
		input.cNameDefault = input.className;
		input.cNameActive  = "search_input_active";
		
		input.on("focus",function(){
			if(input.value == input.defaultValue){
				input.value = "";
				input.className = input.cNameActive;
			}
		});
		input.on("blur",function(){
			if(input.value == ""){
				input.value = input.defaultValue;
				input.className = input.cNameDefault;
			}
		});
		
		input.value = "";
		input.className = input.cNameActive;
	},
	toggleSearch: function(){
		if(this.toggle_search == true){
			this.toggle_search = false;
			this.contractSearch();
		} else {
			this.toggle_search = true;
			this.expandSearch();
		}
	},
	initDatepicker: function(){
		var dp = $('datepicker').select("[rel='datepicker']");
		if(dp[0].dpk == undefined){
			dp.each(function(e,i){
				var btn = e.next("input",0).id = e.id+"_btn";
				
				e.dpk = new DatePicker({
					relative: e.id,
					enableYearBrowse: true,
					disableFutureDate: true,
					topOffset: 25,
					leftOffset: 0,
					range:{
						index:i,
						id:(e.id=="date_from"?"date_to":"date_from")
					},
					externalControl:btn
				});
			});
		}
	},
	expandSearch: function(){
		this.initDatepicker();
		
		$('extended_search').show();
		$('search_type').value = "extended";
	},
	contractSearch: function(){
		$('extended_search').hide();
		$('search_type').value = "videos";
	}
};
document.observe("dom:loaded",main.init.bind(main));

var mail = {
	url: "",
	current_form: null,
	init: function(){
	},
		
	ajax: function(paramaters, callback, callbackError){
		if(callback == undefined){
			callback = Prototype.emptyFunction;
		}
		if(callbackError == undefined){
			callbackError = callback;
		}
		new Ajax.Request(this.url+"/mail.ajax",{
			parameters:paramaters,
			onSuccess: function(t){				
				var response = t.responseText;
				if(response.isJSON()){
					response = response.evalJSON();
					if(response.error && Object.isFunction(callbackError)){
						callbackError(response, true);
					} else if(Object.isFunction(callback)){
						callback(response, false);
					}
				}
			}.bind(this)
		});
	},
	
	formClear: function(){
		if(this.current_form != undefined){
			this.current_form.getElements().each(function(e,i){
				if(e.className != "btn_mail_send"){
					e.value = "";
				}
			});
			
			this.current_form = null;
		}
	},
	
	formRequest: function(action,modul,id,element){
		if(Object.isElement(element)){
			if(this.formQuickie(element) == true){
				this.current_form = $(element);
				
				var parameters  = {
					action: action,
					modul: modul,
					id:	id
				};
				
				var arr_type = ["text","password","textarea","radio","checkbox","select","hidden"];
				var form = $(element).getElements().each(function(e,i){
					if((arr_type.indexOf(e.type) != -1)){
						parameters[e.name] = e.value;
					}			
				});
				
				this.ajax(parameters, this.formRequestAnswer.bind(this));
			}
		}
	},
	
	formRequestAnswer: function(answer, error){
		if(answer.action != undefined){
			switch(answer.action){
				case "mail_advise":						
						this.handleMailAdviseAnswer(answer, error);
					break;
			}
		}
	},

	formQuickie: function(element){
		var check = true;
		var arr_type = ["text","password","textarea","radio","checkbox","select"];
		var form = $(element).getElements().each(function(e,i){			
			if((arr_type.indexOf(e.type) != -1) && (e.readAttribute("rel") == "must_have") && (e.value.empty())){				
				check = false;
				e.setStyle({border: '1px solid #880000'});
			} else {
				var found = e.name.toLowerCase().search(/email/);
				if(found != -1 && (e.readAttribute("rel") == "must_have") && !this.validateEmail(e.value)){
					check = false;
					e.setStyle({border: '1px solid #880000'});					
				} else {
					e.setStyle({border: '1px solid #706C90'});
				}
			}
		}.bind(this));
		
		if(!check){
			this.showMessage('Bitte füllen Sie alle Pflichtfelder aus!');
		}
		
		return check;
	},

	validateEmail: function(email){
		var regex = new RegExp("^([a-zA-Z0-9\\-\\.\\_]+)(\\@)([a-zA-Z0-9\\-\\.]+)(\\.)([a-zA-Z]{2,6})$"); 
		var res = (regex.test(email));
	
		return res;
	},
	
	clearMessage: function(){
		if($('msg')){
			$('msg_text').innerHTML = "";
			$('msg_closer').hide();
			$('msg').hide();
		}
	},
		
	showMessage: function(msg, error){
		if(error == undefined){
			var error = true;
		}
		
		if($('msg')){
			var element = $('msg');
			if(error == false){
				$('msg_text').className = "fqmg_ok";
			} else {
				$('msg_text').className = "fqmg_error";
			}
			$('msg_text').update(msg);
			element.show();
		} else {
			alert(msg);
		}
	},
	
	showMessageCloser: function(){
		if($('msg')){
			$('msg_closer').show();
		}
	},
	
	toggleMailAdvise: function(){
		this.clearMessage();
		$('mail_advise').toggle();
	},
	
	handleMailAdviseAnswer: function(answer, error){
		if(error == undefined){
			var error = false;
		}
		
		if(error == false){
			$('mail_advise').hide();
			this.formClear();
			//Recaptcha.reload();
			this.showMessage(answer.message, error);
			this.showMessageCloser();
			window.setTimeout(this.clearMessage.bind(this), 8000);
		} else {
			//Recaptcha.reload();
			this.showMessage(answer.message, error);
		}
	}
};

var TextCutter = Class.create({
	node: null,
	counter: null,
	counterClassName: "char_counter",
	createCounter: true,
	createWrap: false,
	onlyInt: false,
	wrapStyle: "",
	counterObj:{chars:0},
	counterText: "Sie können noch #{chars} Zeichen schreiben",
	maxChars:20,
	initialize: function(element,options){
		if($(element)){
			this.node = $(element);
			
			if(!Object.isUndefined(options)){
				if(!Object.isUndefined(options.createCounter))
					this.createCounter = options.createCounter;
				
				if(!Object.isUndefined(options.maxChars))
					this.maxChars = options.maxChars;
				
				if(Object.isString(options.counterText))
					this.counterText = options.counterText;
				
				if(Object.isString(options.counterClassName))
					this.counterClassName = options.counterClassName;
				
				if(!Object.isUndefined(options.createWrap))
					this.createWrap = true;
				
				if(Object.isString(options.wrapStyle))
					this.wrapStyle = options.wrapStyle;
			}
			
			if(this.node.tagName == "TEXTAREA"){
				this.node.wrap = "physical";
			}
			
			if(this.node.readAttribute("maxlength")){
				var maxChars = parseInt(this.node.readAttribute("maxlength"));
				if(maxChars>0){
					this.maxChars = maxChars;
				}
			}
						
			this.node.observe("keydown",function(){
				this.countChars();
			}.bindAsEventListener(this));
			// nur zahlen im inputfeld stehen lassen
			this.node.observe("keyup",function(event){
				if(this.onlyInt){
					var element = Event.element(event);
					var val = element.value.replace(/[^\d]/g,"");
						element.value = val;
				}
				this.countChars();
			}.bindAsEventListener(this));
			
			if(this.createCounter){
				this.buildCounter();
			}
			
			this.countChars();
		}
	},
	buildCounter: function(){
		this.counterText = new Template(this.counterText);
		this.counterObj.chars = this.maxChars;
		this.counter = new Element("div",{className:this.counterClassName}).insert(this.counterText.evaluate(this.counterObj));
		
		if(this.createWrap){
			this.wrap = new Element("div",{style:this.wrapStyle})
			Element.wrap(this.node, this.wrap);
			this.wrap.insert(this.counter);
		} else {
			this.node.insert({after:this.counter});
			//.setStyle({display:"inline"})
		}
	},

	countChars: function(){
		if($F(this.node).length > this.maxChars){
			this.node.value = $F(this.node).substring(0, this.maxChars);
			this.countChars();
		} else {
			if(Object.isElement(this.counter)){
				this.counterObj.chars = this.maxChars - $F(this.node).length;
				this.counter.update(this.counterText.evaluate(this.counterObj));
			}
		}
	}
});
