/* ÄÖÜ UTF-8 */
/**
 * Object to handle form-display stuff
 *
 * requires jQuery 1.4.2
 */
var fm = {
	//
	// Properties
	//
	 curOpen: false
	,initHeight: false
	,bottomMargin: 37
	// die Reihenfolge der Buttons muss zur Reihenfolge der Formulare passen
	,mainbuttons: ["btn_angebot_anfordern", "btn_online_reservierung", "btn_beispielrechnung", "btn_unterlagen_bestellen","btn_cip_beispiel","btn_gcip_beispiel","btn_clp_beispiel", "btn_send_email", "btn_callback", "btn_kontaktbox_send_email", "btn_kontaktbox_callback", "btn_vertrieb_partner"]
	,formLayers:  ["angebot",               "onlinereservierung",      "beispielrechnung",     "unterlagen_bestellen",    "cip_beispiel",    "gcip_beispiel",    "clp_beispiel",     "nachricht",      "callback",     "nachricht",                 "callback"               , "vertrieb_partner"    ]
	,dateSelectors: ["txtMietbeginn"]
	,curProduct: false
	,pdfLinkToOpen: false
	//
	// functions
	//
	/**
	 * initialize
	 */
	,init: function() {
		var urlObj = $.parseUrl(window.location);
		// regex match against current filename to find the right product and attach this info as data to the button
		var path = urlObj.relative;
		path.match(/produkte_und_angebote\/(cip|gcip|clp)_?.*\.html/g);
		var matched = RegExp.$1;
		if (matched.length > 0 && matched != 'index') {
			this.curProduct = matched;
		}
		// fix height of keyvisual Area
		$('#keyvisual').css('height', $('#keyvisual').height());
		this.curOpen = $("#empty");
		this.initHeight = this.curOpen.height();
		// an die Buttons IM LAYER binden
		jQuery.each(this.mainbuttons, $.proxy(this, "bindToMainButton") );
		// an die Links in der Promobox binden
		jQuery.each($('#promoCIP_on a'),  $.proxy(this, "bindToPromoButton"));
		jQuery.each($('#promoGCIP_on a'), $.proxy(this, "bindToPromoButton"));
		jQuery.each($('#promoCLP_on a'),  $.proxy(this, "bindToPromoButton"));

		$('#empty').before('<span id="dynLoadedForm" style="padding:0; margin:0; height:0;"></span>');

		/**
		 * Check urlObj for param "of" (openForm)
		 *
		 */
		var params = urlObj.params;
		if (typeof params.of != 'undefined') {
			switch (params.of) {
				case 'bsp': //Beispielrechung
					$('#btn_beispielrechnung').trigger('click');
					break;
				case 'res': // Onlinereservierung
					$('#btn_online_reservierung').trigger('click');
					break;
				case 'bst': // Unterlagen bestellen
					$('#btn_unterlagen_bestellen').trigger('click');
					break;
			}
		}
	}
	/**
	 * resets everything to initial state (no Form open)
	 */
	,resetFormLayer: function() {
		$('#subnav a').removeClass('active');
		this.curOpen.hide();
		$('#keyvisual').animate({
			height: this.initHeight
			}, 500
		);
		this.curOpen = $("#empty");
		$('#dynLoadedForm *').remove();
		this.curOpen.show();
		return false;
	}
	/**
	 * shows "danke" Page after a (successful) Form submit
	 */
	,showDankeLayer: function() {
		var dankeId = 'danke_'+this.curOpen.attr('id');
		// console.log(dankeId);
		$('#dynLoadedForm *').remove();
		$('#dynLoadedForm').load('/dev/all_danke.php #'+dankeId, $.proxy( function() {
			var form = $('#'+dankeId);
			this.curOpen.hide();
			$('#keyvisual').animate({
				height: form.height()+this.bottomMargin
				}, 500, function() {
						form.show();
					}
			);
			this.curOpen = form;
			$("a.close", this.curOpen).bind('click', $.proxy(this, "resetFormLayer"));
			return false;
		}, this));
		return false;
	}
	/**
	 * show a Form, based on clicked button
	 */
	,showFormLayer: function(event) {
		// Subnav buttons in Keyvisual Bereich
		var subnav = $('#subnav a');
		if (subnav.length != 0) {
			subnav.removeClass('active');
		}

		// store current event target
		var curT = $(event.currentTarget);
		var curTId = curT.attr("id");
		var formId = ""; var index; var form;
		// split between serveral buttons/links that open a Form
		if (curTId == "btn_send_email" || curTId == "btn_callback" || curTId == "btn_kontaktbox_send_email" || curTId == "btn_kontaktbox_callback" || curTId == "btn_vertrieb_partner") {
			curT.addClass('active');
			index = $.inArray(curTId, this.mainbuttons);
			form = $("#"+this.formLayers[index]);
			formId = this.formLayers[index];
		} else if ( ( (curT.parent().attr("id") == "subnav") || (curT.parent().attr("id") == "copy") ) || curT.parents('#beispielrechnung').length != 0 ) { // click in keyvisual Bereich oder in "Beispielrechnung" Verteil-Seite
			curT.addClass('active');
			if (this.curProduct && curTId == "btn_beispielrechnung") { // übrspringe die Verteil-Seite, wenn das Produkt bekannt ist und auf "Beispielrechnung" geklickt wurde
				index = $.inArray("btn_"+this.curProduct+"_beispiel", this.mainbuttons);
			} else {
				index = $.inArray(curT.attr('id'), this.mainbuttons);
			}
			form = $("#"+this.formLayers[index]);
			formId = this.formLayers[index];
		} else { // click in Promobox
			var product = curT.data('product');
			if (curT.hasClass('promo1')) { // PDF Download - wird nie aufgerufen, da an den Klick event keine Aktion gebunden ist.
				form = $("#angebot");
				formId = 'angebot';
				$('#btn_angebot').addClass('active');
			} else if (curT.hasClass('promo2')) { // Onlinereservierung
				form = $("#onlinereservierung");
				formId = 'onlinereservierung';
				$('#btn_online_reservierung').addClass('active');
			} else if (curT.hasClass('promo3')) { // Beispielrechner
				form = $("#" + product.toLowerCase() + "_beispiel");
				formId = product.toLowerCase() + "_beispiel";
				$('#btn_beispielrechnung').addClass('active');
			} else if (curT.hasClass('promo4')) { // Detailinformationen
				form = $("#unterlagen_bestellen");
				formId = "unterlagen_bestellen";
				$('#btn_unterlagen_bestellen').addClass('active');
			}
		}
		// Scroll window
		if ($(window).scrollTop() > 0) {
			$(window).scrollTop(0);
		}

		this.formIdToLoad = formId;
		// console.log(formId);
		$('#dynLoadedForm *').remove();
		$('#dynLoadedForm').load('/dev/all_forms.php #'+formId, $.proxy( function() {
			var form = $('#'+this.formIdToLoad);
			this.curOpen.hide();
			$('#keyvisual').animate({
				height: form.height()+this.bottomMargin
				}, 500, function() {
						form.show();
					}
			);
			this.curOpen = form;
			this.attachValidator();
			$("a.close", this.curOpen).bind('click', $.proxy(this, "resetFormLayer"));
			// wenn der aktuelle Layer die Beispiel-Rechnung Verteilseite ist,
			// muss an die drei Links ein Click Event gebunden werden
			if (this.formIdToLoad == "beispielrechnung") {
				jQuery.each(["btn_cip_beispiel","btn_gcip_beispiel","btn_clp_beispiel"], $.proxy(this, "bindToMainButton") );
			}
			// Wenn Formular "Onlinereservierung", dann hole Attribut angebotnr von event source element und füge den wert ins formular ein
			if (this.formIdToLoad == 'onlinereservierung' && curT.hasClass('promo2')) {
				$('#angebotnr').attr('value',curT.attr('angebotnr'));
			}
			// Wenn Formular "Unterlagen bestellen", überwache change auf #produktbroschuere
			if (this.formIdToLoad == 'unterlagen_bestellen') {
				$('#produktbroschuere').change(function(event) {
					if ($(event.currentTarget).is(':checked')) {
						$('#cip_broschuere').attr('checked','checked');
						$('#gcip_broschuere').attr('checked','checked');
						$('#clp_broschuere').attr('checked','checked');
					} else {
						$('#cip_broschuere').removeAttr('checked');
						$('#gcip_broschuere').removeAttr('checked','checked');
						$('#clp_broschuere').removeAttr('checked','checked');
					}
				})
			}
			return false;
		}, this));
		return false;
	}
	/**
	 * bind showFormLayer method to click event on buttons (if they exists)
	 */
	,bindToMainButton: function(/*integer*/ index, /*string*/ buttonId) {
		var btn = $('#'+buttonId);
		if (btn.length != 0) { // Element exists
			btn.bind('click', $.proxy(this, "showFormLayer") );
		}
	}
	/**
	 * conditionally bind showFormLayer method to click event on Links in PromoBox
	 */
	,bindToPromoButton: function(/*integer*/ index, /*DOMObj*/ link) {
		var product = "";
		var jLink = $(link);
		var curId = jLink.parent().attr("id");
		if (curId.match(/GCIP/)) {
			product = "GCIP";
		} else if (curId.match(/CLP/)) {
			product = "CLP"
		} else if (curId.match(/CIP/)) {
			product = "CIP"
		}
		jLink.data('product',product);
		// always add target to promo1, since this is a pdf link 
		if (jLink.hasClass('promo1')) {
			jLink.attr('target','_blank');
			return;
		}
		// bbak 2010-11-09: nur binden, wenn das aktuelle Produkt passt, sonst hinterlegten Link aufrufen
		if (product.toLowerCase() == this.curProduct) {
			jLink.bind('click',$.proxy(this, "showFormLayer") );
		}
	}
	/**
	 * attaches the validator to the currently opened form
	 *
	 * additionally attaches a Date-Selector to CLP
	 */
	,attachValidator: function() {
		var form = $('form', this.curOpen);
		switch (form.attr("id")) {
			case "formOffer":
				form.validate({
					onkeyup: false /* no validation on Key up */
					,rules: {
						anrede: "required"
					   ,name: "required"
					   ,vorname: "required"
					   ,strasse: "required"
					   ,PLZ: "required"
					   ,ort: "required"
					   ,land: "required"
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/form.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,resetForm:     true          // reset the form after successful submit
							,timeout:       3000
							// ,success:       $(location).attr('href','/kontakt/mail_danke.html')
							,success:       $.proxy(this, "showDankeLayer")
						});
						return false;
					}, this)
					// this disables the error Messages
					,showErrors: showErrors
				});
				break;
			case "formSalesPartner":
				form.validate({
					 onkeyup: false // no validation on Key up
					,groups: {
						aufmerksam: "aufmerksam1 aufmerksam2 aufmerksam3 aufmerksam_sonstiges"
					}
					,rules: {
						 "aufmerksam[]": { required: false ,minlength: 1}
						,"aufmerksam_sonstiges": {
							required: function(element) {
								if(!$("#aufmerksam1").is(":checked") && !$("#aufmerksam2").is(":checked") && !$("#aufmerksam3").is(":checked")){
									return true;
								}
								return false;
							}
						}
						,anrede: "required"
						,name: "required"
						,vorname: "required"
						,strasse: "required"
						,PLZ: "required"/*{
							required: true,
							digits: true,
							minlength: 4,
							maxlength: 5
						 }*/
						,ort: "required"
						,land: "required"
						,mobil:{
							required: function(element) {
								if($("#perMobile").is(":checked")){
									return true;
								}
								return false;
							}
						}
						,fon: "required"
						,email: "required email"
						
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/form.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,timeout:       3000
							,success:       $.proxy(this, "showDankeLayer")
						});
						return false;
					}, this)
					,invalidHandler: function(form, validator) {
						var errors = validator.numberOfInvalids();
						if (validator.errorMap['aufmerksam'] || validator.errorMap['aufmerksam_sonstiges']) {
							$('#aufmerksam1_error').show();
						} else {
							$('#aufmerksam1_error').hide();
						}
					}
					// this disables the error Messages
					,showErrors: showErrors
				});
			case "formReservation":
				form.validate({
					 onkeyup: false // no validation on Key up
					,rules: {
						 containeranzahl: "required"
						,angebotnr: "required"
						,anrede: "required"
						,name: "required"
						,vorname: "required"
						,strasse: "required"
						,PLZ: "required"
						,ort: "required"
						,land: "required"
						,berater: "required"
						,email: {
							email: true,
							required: function() {
								return ( $('#formReservation #angebotemail').is(":checked") && $('#email').val().length == 0)
							}
						}
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/form.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,timeout:       3000
							,success:       $.proxy(this, "showDankeLayer")
							// ,success:       $(location).attr('href','/kontakt/onlinereservierung_danke.html')
						});
						return false;
					}, this)
					// this disables the error Messages
					,showErrors: showErrors
				});
				break;
			case "formOrderFiles":
				form.validate({
					 onkeyup: false // no validation on Key up
					,rules: {
						 "broschuere[]": { required: true ,minlength: 1}
						,anrede: "required"
						,name: "required"
						,vorname: "required"
						,strasse: "required"
						,PLZ: "required"
						,ort: "required"
						,land: "required"
						,berater: "required"
						,email: {
							email: true,
							required: function() {
								return ( $('#formOrderFiles #angebotemail').is(":checked") && $('#email').val().length == 0)
							}
						}
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/form.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,resetForm:     true          // reset the form after successful submit
							,timeout:       3000
							// ,success:       $(location).attr('href','/kontakt/unterlagenanfordern_danke.html')
							,success:       $.proxy(this, "showDankeLayer")
						});
						return false;
					}, this)
					// this disables the error Messages
					,showErrors: showErrors
					,invalidHandler: function(form, validator) {
						var errors = validator.numberOfInvalids();
						if (validator.errorMap['broschuere[]']) {
							$('#broschuere_error').show();
						} else {
							$('#broschuere_error').hide();
						}
					}

				});
				break;
			case "formExampleCLP":
				// jquery.ui.date an Datumsfelder binden
				jQuery.each(this.dateSelectors, function(index, dateFieldId){
						$('#'+dateFieldId ).datepicker($.datepicker.regional['de']);
						$('#'+dateFieldId ).datepicker( "option", "minDate", "+1" );
					})
				form.validate({
					 onkeyup: false
					,rules: {
						 Datum: "required"
						,Anzahl: {
							required: true,
							digits: true,
							range: [1, 300]
						}
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/examplePdfProxy.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,async: false                 // prevent async processing since the success method sets
							                              // fm.pdfLinkToOpen which is used later to open a (blocker-free)
														  // popup-window
							,resetForm:     true          // reset the form after successful submit
							,timeout:       10000
							,success:       function(response, status, xhr, form) {
								if (0 == parseInt(response.errorcode)) {
									var re = /dev\.wob\.ag/;
									var host;
									host = location.hostname.match(re) ? 'www.pundr.de' : location.hostname;
									fm.pdfLinkToOpen = 'http://' + host + response.filename;
									// window.location.href = 'http://'+host+response.filename;
									// var w = window.open('http://'+host+response.filename);
									// Opening a new Window doesn't work due to popup blockers
								} else {
									alert('Es ist ein interner Fehler aufgetreten.\nBitte versuchen Sie es später nocheinmal.');
								}
							}
						});
						if (this.pdfLinkToOpen) {
							// console.log(this.pdfLinkToOpen);
							var w = window.open(this.pdfLinkToOpen,'angebot',"location=yes,menubar=no,toolbar=no,");
							this.pdfLinkToOpen = false;
						}
						return false;
					}, this)
					// this disables the error Messages
					,showErrors: showErrors
				});
				break;
			case "formExampleCIP":
				form.validate({
					 onkeyup: false
					,rules: {
						 Anzahl: {
							required: true,
							digits: true,
							range: [1, 300]
						 }
						,Steuer1: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer2: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer3: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer4: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer5: {
							required: true,
							digits: true,
							range: [0,99]
						}
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/examplePdfProxy.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,async: false                 // prevent async processing since the success method sets
							                              // fm.pdfLinkToOpen which is used later to open a (blocker-free)
														  // popup-window
							,resetForm:     true          // reset the form after successful submit
							,timeout:       10000
							,success:       function(response, status, xhr, form) {
								if(parseInt(response.errorcode) == 0) {
									var re = /dev\.wob\.ag/; var host;
									host = location.hostname.match(re) ? 'www.pundr.de' : location.hostname;
									fm.pdfLinkToOpen = 'http://'+host+response.filename;
									// window.location.href = 'http://'+host+response.filename;
									// var w = window.open('http://'+host+response.filename);
									// Opening a new Window doesn't work due to popup blockers
								} else {
									alert('Es ist ein interner Fehler aufgetreten.\nBitte versuchen Sie es später nocheinmal.');
								}
							}
						});
						if (this.pdfLinkToOpen) {
							// console.log(this.pdfLinkToOpen);
							var w = window.open(this.pdfLinkToOpen,'angebot',"location=yes,menubar=no,toolbar=no,");
							this.pdfLinkToOpen = false;
						}
						return false;
					}, this)
					,showErrors: showErrors
				});
				break;
			case "formExampleGCIP":
				form.validate({
					 onkeyup: false
					,rules: {
						 Anzahl: {
							required: true,
							digits: true,
							range: [1, 300]
						 }
						,Steuer1: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer2: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer3: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer4: {
							required: true,
							digits: true,
							range: [0,99]
						}
						,Steuer5: {
							required: true,
							digits: true,
							range: [0,99]
						}
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/examplePdfProxy.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,async: false                 // prevent async processing since the success method sets
							                              // fm.pdfLinkToOpen which is used later to open a (blocker-free)
														  // popup-window
							,resetForm:     true          // reset the form after successful submit
							,timeout:       10000
							,success:       function(response, status, xhr, form) {
								if(parseInt(response.errorcode) == 0) {
									var re = /dev\.wob\.ag/; var host;
									host = location.hostname.match(re) ? 'www.pundr.de' : location.hostname;
									fm.pdfLinkToOpen = 'http://' + host + response.filename;
									// window.location.href = 'http://'+host+response.filename;
									// var w = window.open('http://'+host+response.filename);
									// Opening a new Window doesn't work due to popup blockers
								} else {
									alert('Es ist ein interner Fehler aufgetreten.\nBitte versuchen Sie es später nocheinmal.');
								}
							}
						});
						if (this.pdfLinkToOpen) {
							// console.log(this.pdfLinkToOpen);
							var w = window.open(this.pdfLinkToOpen,'angebot',"location=yes,menubar=no,toolbar=no,");
							this.pdfLinkToOpen = false;
						}
						return false;
					}, this)
					,showErrors: showErrors
				});
				break;
			case "formCallBack":
				// display input for kundennummer according to radio button
				$("input[name='kunde']").click(function(e) {
					var t = $(e.currentTarget);
					if (t.val() == "Ja") {
						$('#kundennummernfrage').show();
					} else {
						$('#kundennummernfrage').hide();
					}
				});
				// display input for vertragsnummer according to radio button
				$("input[name='vertragsfrage']").click(function(e) {
					var t = $(e.currentTarget);
					if (t.val() == "Ja") {
						$('#vertragsnummernfrage').show();
					} else {
						$('#vertragsnummernfrage').hide();
					}
				});

				form.validate({
					 onkeyup: false
					,rules: {
						 kunde: "required"
						,vertragsnummer: {
							required: function(elem) {
								return ( $('#formCallBack #vertragsfrageja').is(":checked") && $('#vertragsnummer').val().length == 0)
							}
						}
						,anrede: "required"
						,name: "required"
						,vorname: "required"
						,email: "email"
						,fon: "required"
						,"zeitfenster[]": { required: true, minlength: 1 }
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/form.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,resetForm:     true          // reset the form after successful submit
							,timeout:       3000
							,success:       $.proxy(this, "showDankeLayer")
						});
						return false;
					}, this)
					,invalidHandler: function(form, validator) {
						var errors = validator.numberOfInvalids();
						if (validator.errorMap['zeitfenster[]']) {
							$('#zeitfenster_error').show();
						} else {
							$('#zeitfenster_error').hide();
						}
					}
					,showErrors: showErrors
				});
				break;
			case "formMail":
				// display input for kundennummer according to radio button
				$("input[name='kunde']").click(function(e) {
					var t = $(e.currentTarget);
					if (t.val() == "Ja") {
						$('#kundennummernfrage').show();
					} else {
						$('#kundennummernfrage').hide();
					}
				});
				// display input for vertragsnummer according to radio button
				$("input[name='vertragsfrage']").click(function(e) {
					var t = $(e.currentTarget);
					if (t.val() == "Ja") {
						$('#vertragsnummernfrage').show();
					} else {
						$('#vertragsnummernfrage').hide();
					}
				});

				form.validate({
					 onkeyup: false
					,rules: {
						 kunde: "required"
						,vertragsnummer: {
							required: function(elem) {
								return ( $('#formMail #vertragsfrageja').is(":checked") && $('#vertragsnummer').val().length == 0)
							}
						}
						,anrede: "required"
						,name: "required"
						,vorname: "required"
						,email: {
							 email: true
							,required: function(elem) {
								return !( $('#formMail #email').val().length != 0 || $('#formMail #fon').val().length != 0 );
							}
						}
						,fon: {
							required: function(elem) {
								return !( $('#formMail #email').val().length != 0 || $('#formMail #fon').val().length != 0 );
							}
						}
						,mesage: "required"
						,"zeitfenster[]": { required: true, minlength: 1 }
					}
					,submitHandler: $.proxy( function(form) {
						$(form).ajaxSubmit({
							 url:           "/_ajax/form.php"   // override for form's 'action' attribute
							,type:          "post"        // 'get' or 'post', override for form's 'method' attribute
							,dataType:      "json"        // 'xml', 'script', or 'json' (expected server response type)
							,resetForm:     true          // reset the form after successful submit
							,timeout:       3000
							,success:       $.proxy(this, "showDankeLayer")
						});
						return false;
					}, this)
					,invalidHandler: function(form, validator) {
						var errors = validator.numberOfInvalids();
						if (validator.errorMap['zeitfenster[]']) {
							$('#zeitfenster_error').show();
						} else {
							$('#zeitfenster_error').hide();
						}
					}
					,showErrors: showErrors
				});
				break;
		}
	}
};
/**
 * Custom Function to display validation errors
 *
 */
var showErrors = function() {
	var i;
	for (i = 0; this.errorList[i]; i++) {
		var error = this.errorList[i];
		//console.log(error);
		this.settings.highlight && this.settings.highlight.call(this, error.element, this.settings.errorClass, this.settings.validClass);
		// this.showLabel(error.element,error.message);
	}
	if (this.errorList.length) {
		this.toShow = this.toShow.add(this.containers);
	}
	if (this.settings.success) {
		for (i = 0; this.successList[i]; i++) {
			this.showLabel(this.successList[i]);
		}
	}
	if (this.settings.unhighlight) {
		var elements;
		for (i = 0,elements = this.validElements(); elements[i]; i++) {
			this.settings.unhighlight.call(this, elements[i], this.settings.errorClass, this.settings.validClass);
		}
	}
	this.toHide = this.toHide.not(this.toShow);
	this.hideErrors();
	this.addWrapper(this.toShow).show();
}
//
// MAIN
//
$(document).ready(function() {
	/**
	 * Extend jquery with a fast URL Parser function
	 */
	$.extend({
		parseUrl: function(url) {
			var a =  document.createElement('a');
			a.href = url;
			return {
				source: url,
				protocol: a.protocol.replace(':',''),
				host: a.hostname,
				port: a.port,
				query: a.search,
				params: (function(){
					var ret = {},
						seg = a.search.replace(/^\?/,'').split('&'),
						len = seg.length, i = 0, s;
					for (;i<len;i++) {
						if (!seg[i]) { continue; }
						s = seg[i].split('=');
						ret[s[0]] = s[1];
					}
					return ret;
				})(),
				file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
				hash: a.hash.replace('#',''),
				path: a.pathname.replace(/^([^\/])/,'/$1'),
				relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
				segments: a.pathname.replace(/^\//,'').split('/')
			};
		}
	});
	/**
	 * Analyze path to mark the correct Topnav Element active
	 */
	var path = $.parseUrl(window.location).path;
	var activeId = "";
	var pattern = /\/([^\/]*)\//i;
	var matches = path.match(pattern);
	if( matches) {
		switch (matches[1]) {
			case 'unternehmen':
				$('#nav1').addClass('active');
				break;
			case 'produkte_und_angebote':
				$('#nav2').addClass('active');
				break;
			case 'gesellsch_verantwortung':
				$('#nav3').addClass('active');
				break;
			case 'faszination_container':
				$('#nav4').addClass('active');
				break;
			case 'presse':
				$('#nav5').addClass('active');
				break;
			case 'kontakt':
				$('#nav6').addClass('active');
				break;
		}
	}
	/**
	 * init form stuff
	 */
	fm.init();
});
