formToArray = function(form, buttonName, linkId) {
	var a = {};
	var els = $('input,select,textarea',form);
	if (!els){return a;}
	// loop over all fields...
	for(var i=0, max=els.length; i < max; i++) {
	  var el = els[i];
	  // grab name attribute as identifier...
	  var n = $(el).attr('name');
	  // no name - ignore field
	  if (!n) continue;
	  // only submit die button clicked
	  if(el.type=='submit' && n != buttonName) continue;
	  // in case it is a radio or checkbox field and not checked - ignore field
	  if((el.type=='radio' || el.type=='checkbox') && !el.checked) {continue;}
	  // get the value..
	  var v = $(el).val();
	  // value not set - put it into the array object
	  if(!a[n] || typeof(a[n])=='undefined') {
	    a[n]=v;
    	//alert("Feld:" + n + " Wert:" + v);
	  } else {
	    // already set - create an neseted array...
	    var temp = a[n];
	    var value = [];
	    // it is already an array..
	    if(typeof(temp)=='Array') {
	      value = temp;
	    } else {
	      // no array add value to the new one
	      value.push(temp);
	    }
	    // add the current value to subset
	    value.push(v);
	    a[n] = value;
	  }
	  //bei geklicktem Link hier noch die LinkId übertragen
	  if(linkId != '') {
        a[linkId] = 'true';
      }
	}
	return a;
};

  AjaxFormHandler = function(   ) {
     // grab url and type from form element
     var url = $(form).attr('action');
     // var type = $(form).attr('method').toUpperCase();
     $('a, button[type="submit"],input[type="submit"]',form).click(function(){
        // override default submit and get all data from form
        var data = formToArray(form,$(this).attr("name"),$(this).attr("id"));
    	// var data = $(form).serialize();
        // form.reset();
        // do an ajax request,
        // response can be any html (another form) or success message
        $.ajax({
           'type': 'POST',
           'url': url,
           'data': data,
           'success': function(html){
              // the response should be html syntax...
              $('#dynlayerdiv').html(html).show();
              // in case the container now contains a form...
              if($('form','#dynlayerdiv').size() > 0) {
                form = $('form','#dynlayerdiv')[0];
                // initialize the form handler again
                AjaxFormHandler(form);
              }
            }
        });
        return false;
     });
  };

$().ready( function() {
	if (location.href.match("dynaLayer=")) {
		dynaLayerUrl=location.href.substring(location.href.search("dynaLayer=") + 10);
		var dynaLayerKlick = false;
		$('.ajax').each( function() {
			var url = $(this).attr('href');
			if (url == dynaLayerUrl && dynaLayerKlick == false) {
				dynaLayerKlick = true;
				clickA(this);
				return false;
			}
		})
	}
});

$().ready( function() {
	$('#dynlayerdiv').html('');
	$('#dynlayerdiv').hide();
	// first looking for all elements with the class 'ajax'
	$('.ajax').each( function() {
		// in case it is a normal link...
			if (this.nodeName.toLowerCase() == 'a') {
				$(this).click( function() {
					clickA(this);
					return false;
				});
				// in case it is a form
			} else if (this.nodeName.toLowerCase() == 'form') {
				// initialize the form handler
				AjaxFormHandler(this);
			}
			// return false;
		});
});

function clickA(anchor) {
	$('#dynlayerdiv').html('');
	// using the href attribute to receive the form...
	var url = $(anchor).attr('href');
	if (url.match("^.*/(kontakt|schadenmeldung|mitteilung|kuendigung|beratungswunsch|nachricht|meinedaten).do")) {
		// ggf. Umschalten auf https
        var result = parseURL(location.href);
		if (result.protocol == "http") {
			port = "";
			if (result.port == 8080) {
				port = ":8443";
			}
			location.href = "https://" + result.host + port + result.path + "?dynaLayer=" + url;
			return;
		}
    }

	$.ajax({
		'type' :'POST',
		'url' :url,
		'success' : function(html) {
		  var formName = '';
			// the response should be html syntax...
			$('#dynlayerdiv').html(html).show();
			// in case the container now contains a form...
			if ($('form', '#dynlayerdiv').size() > 0) {
				form = $('form', '#dynlayerdiv')[0];
				formName = form.name;
				// initialize the form handler
				AjaxFormHandler(form);
			}
			window.scrollTo(0, 0);
			showForm('_dynlayer');
			if (formName != '') {
			  focusFirstFormField(formName);
			}
			$('._dynlayer .HideSelect').css({
				'height' :'58em'
			});
		}
	});
}


function parseURL(buffer) {
	var result = {};
	result.protocol = "";
	result.user = "";
	result.password = "";
	result.host = "";
	result.port = "";
	result.path = "";
	result.query = "";

	var section = "PROTOCOL";
	var start = 0;
	var wasSlash = false;

	while (start < buffer.length) {
		if (section == "PROTOCOL") {
			if (buffer.charAt(start) == ':') {
				section = "AFTER_PROTOCOL";
				start++;
			} else if (buffer.charAt(start) == '/'
					&& result.protocol.length() == 0) {
				section = PATH;
			} else {
				result.protocol += buffer.charAt(start++);
			}
		} else if (section == "AFTER_PROTOCOL") {
			if (buffer.charAt(start) == '/') {
				if (!wasSlash) {
					wasSlash = true;
				} else {
					wasSlash = false;
					section = "USER";
				}
				start++;
			} else {
				throw new ParseException(
						"Protocol shell be separated with 2 slashes");
			}
		} else if (section == "USER") {
			if (buffer.charAt(start) == '/') {
				result.host = result.user;
				result.user = "";
				section = "PATH";
			} else if (buffer.charAt(start) == '?') {
				result.host = result.user;
				result.user = "";
				section = "QUERY";
				start++;
			} else if (buffer.charAt(start) == ':') {
				section = "PASSWORD";
				start++;
			} else if (buffer.charAt(start) == '@') {
				section = "HOST";
				start++;
			} else {
				result.user += buffer.charAt(start++);
			}
		} else if (section == "PASSWORD") {
			if (buffer.charAt(start) == '/') {
				result.host = result.user;
				result.port = result.password;
				result.user = "";
				result.password = "";
				section = "PATH";
			} else if (buffer.charAt(start) == '?') {
				result.host = result.user;
				result.port = result.password;
				result.user = "";
				result.password = "";
				section = "QUERY";
				start++;
			} else if (buffer.charAt(start) == '@') {
				section = "HOST";
				start++;
			} else {
				result.password += buffer.charAt(start++);
			}
		} else if (section == "HOST") {
			if (buffer.charAt(start) == '/') {
				section = "PATH";
			} else if (buffer.charAt(start) == ':') {
				section = "PORT";
				start++;
			} else if (buffer.charAt(start) == '?') {
				section = "QUERY";
				start++;
			} else {
				result.host += buffer.charAt(start++);
			}
		} else if (section == "PORT") {
			if (buffer.charAt(start) = '/') {
				section = "PATH";
			} else if (buffer.charAt(start) == '?') {
				section = "QUERY";
				start++;
			} else {
				result.port += buffer.charAt(start++);
			}
		} else if (section == "PATH") {
			if (buffer.charAt(start) == '?') {
				section = "QUERY";
				start++;
			} else {
				result.path += buffer.charAt(start++);
			}
		} else if (section == "QUERY") {
			result.query += buffer.charAt(start++);
		}
	}

	if (section == "PROTOCOL") {
		result.host = result.protocol;
		result.protocol = "http";
	} else if (section == "AFTER_PROTOCOL") {
		throw new ParseException("Invalid url");
	} else if (section == "USER") {
		result.host = result.user;
		result.user = "";
	} else if (section == "PASSWORD") {
		result.host = result.user;
		result.port = result.password;
		result.user = "";
		result.password = "";
	}
	return result;
}

function initDynlayer() {
    $('#overlay-form-container_dynlayer').removeClass('multiColumn');
    $('#overlay-form-container_dynlayer').addClass('singleColumnWide');
    $('#dynlayer_form_footer').show();
}