// bad, bad, ugly globals
var PS, PSDom, globalGalleryInstance;
var initAt = new Date().getTime();

/**
 * @class 
 * Application independent Functions
 */
PS_core = Class.create(
/** @lends PS_core */		
{
	/**
	 * @private
	 * */
	initialize: function () {
		this.debug("PS_core initialized - Core functions available now");
	},

	/** 
	 * @description Console-Enabled Browsers Debugging
	 * 
	 * @param {String} message Message string or exception object
	 * @param {String} [loglevel]
	 */
	debug: function (message, loglevel) {
		loglevel = loglevel || "debug";
		
		if (typeof console === "undefined" || typeof console.debug === "undefined") {
			return false;
		}
		
		var isDevSystem = window.location.host.endsWith('parship.office') || window.location.host.endsWith('parship.net') || window.location.host.indexOf('localhost') != -1 ? true : false;
		var forceDebug  = window.location.search.indexOf('jsDebug=true') != "-1" ? true : false;
		var showTime 	= false;
		
		if (isDevSystem || forceDebug) {
			var timeElapsed = "";
			if (showTime) timeElapsed = (new Date().getTime() - initAt) / 1000 + ": ";
			
			if (typeof message === "string" || typeof message === "number" || typeof console.dir === "undefined") {
				console.debug(timeElapsed + Object.inspect(message));
				if (typeof Backstage !== "undefined" && loglevel == 'info') {
					Backstage.addLogEntry(message);
				}
			} else if (typeof message.stack !== "undefined") {
				console.log("CAUGHT EXCEPTION " + message.stack);
			} else {
				console.dir(message);
			}
		}
	}



});	

/**
 * @class 
 * Initialization of DOM. Prepared on dom:loaded
 */
PS_dom = Class.create(
/** @lends PS_dom */	
{
	/**
	 * @private
	 * */
	initialize: function () {
		this.initActionClasses();
		this.initActionIds();
		this.initOtherDomStuff();
		//PS.debug("PS_dom initialized - all Events set to Dom");
	},
	
	/**
	 * @description Initializes all JS-Classes for listed DOM-IDs
	 */
	initActionIds: function initActionIds() {
		var listViewInput = null;
		var elems;

		if ($('ps_testProfilePrefill')) {
			new Helper.PS_fakeInput(); // for Image-Upload
			$("ps_profilePrefillForm").observe("submit", function() {
				if(typeof allInputDefaults != "undefined") allInputDefaults.clearDefaultValuesBeforeSubmit("ps_profilePrefillForm");	
			});
		}
		
		elems = $('ps_field_password_dynamic');
		if (elems) {
			new PageContext.PS_passwordDynamic(elems);
		}
		
		elems = $('ps_field_new_password');
		if (elems) {
			new PageContext.PS_passwordDynamic(elems);
		}
		
		elems = $('ps_field_password');
		if (elems) {
			if(!$('ps_loginPage')) { //do not call on login page
				new PageContext.PS_passwordDynamic(elems);
			}
		}
		
		elems = $('ps_miniImageGallery');
		if (elems) {
			new PageContext.PS_miniImageGallery(elems);
		}
		
		if ($('showInfoLayerOnWelomepage') && $('ps_rightInTheFace')) {
			window.setTimeout("Modalbox.show($('ps_rightInTheFace'), {width: 540, skin: '1', hideCloseLink: false, confirmBeforeClosing: false});", 1500);
		}
		
			
		elem = $('ps_mottoBox');
		if(elem) { 
			theMottoBox = new PageContext.PS_mottoBox(elem);
		}
		
		elem = $('ps_paymentNavTab');
		if (elem) {
			new PageContext.PS_paymentNavTab(elem);
		}
		
		elem = $('ps_openZipMap');
		if (elem) {
			Par.PageContext.zipMap.init();
		}
		
		PS.debug("FINISHED: initActionIds");
	},
	
	/**
	 * @description MAP with CSS-Classnames. All Names are handed to applyClassHandler for DOM initialisation
	 */
	methodMap : {
		ps_disabledButton: function (ele) {
			allDisabledButtons = new Helper.PS_buttonDisable(ele, []);
		},

		ps_inputDefault: function (ele) {
			allInputDefaults =  new Helper.PS_inputDefault(ele);
		},

		ps_pop: function (ele) {
			new Helper.PS_popupHandler(ele);
		},
		
		ps_listViewRow: function (ele) {
			// TODO: fix
			var listViewInput = false;
			if (listViewInput) {
				new PageContext.PS_listViewRow(ele, listViewInput);
			} else {
				new PageContext.PS_listViewRow(ele, null);
			}
		},

		ps_openEditMode: function (ele) {
			if (!ele.hasClassName('ps_editIconDisabled')) {
				new PageContext.PS_showEditBox(ele);
			}
		},

		ps_hideEditBox: function (ele) {
			new PageContext.PS_hideEditBox(ele);
		},

		ps_productBox: function (ele) {
			new PageContext.PS_productBox(ele);
		},

		ps_productBoxWithSeal: function (ele) {
			new PageContext.PS_productBox(ele);
		},

		ps_productBoxWithLargeSeal: function (ele) {
			new PageContext.PS_productBox(ele);
		},

		ps_selectedProduct: function (ele) {
			new PageContext.PS_productBox(ele);
		},

		ps_productBoxHorizontal: function (ele) {
			new PageContext.PS_productBox(ele);
		},

		ps_productBoxHorizontalWithSeal: function (ele) {
			new PageContext.PS_productBox(ele);
		},

		ps_toggle: function (ele) {
			new Helper.PS_toggle(ele);
		},

		ps_charLimit: function (ele) {
			new Helper.PS_inputObserver(ele);
		},

		ps_tooltip: function (ele) {
			new Helper.PS_tooltip(ele);
		},

		ps_resetNoteForm: function (ele) {
			new PageContext.PS_resetNoteForm(ele);
		},

		ps_makeWritableNote: function (ele) {
			new PageContext.PS_makeWritableNote(ele);
		},

		ps_reportProfile: function (ele) { //for readmessage Page
			new PageContext.PS_reportProfile(ele);
		},

		ps_searchFilters: function (ele) {
			new PageContext.PS_searchFilters(ele);
		},

		ps_editUploadedImages: function (ele) {
			new PS_editUploadedImages(ele);
		},

		ps_welcomeMail: function (ele) {
			new PageContext.PS_welcomeMail(ele);
		},
		
		ps_sorting: function (ele) {
			new PageContext.PS_sorting(ele);
		},
		
		ps_introLinks: function (ele) {
			ele = $$('.ps_introLinks a');
			new PageContext.PS_introLinks(ele);
		},

		ps_pollBox: function () {//In Editorial
			new PageContext.PS_potw().displayCms();
		},
		
			
		/* search criteria country region stuff */
		ps_checkerCheckbox: function (ele) {
			//elem = new PageContext.basiccriteriaRegions();
			elem = new Helper.checkboxChecker();
			elem.checkAllInput(ele);
		},
		ps_singleCheckbox: function (ele) {
			//elem = new PageContext.basiccriteriaRegions();
			elem = new Helper.checkboxChecker();
			elem.singleCheckbox(ele);
		},
		ps_saveCriteriaBtn: function (ele) {
			//elem = new PageContext.basiccriteriaRegions();
			elem = new Helper.checkboxChecker();
			elem.disableCheckAllInput(ele);
		},
				
		ps_hasError: function (ele) {
			if($$('.ps_errorHeadline')[0] != null) { //just on Pages that have an error Summary (long Pages)
				new Helper.PS_hasError(ele);
			}
		},
			
		/**
		 * To be removed after macro #reciprocalModal has been removed (after Funmatch refactor)
		 * @deprecated
		 */
		ps_ac_reciprocal: function (ele) {
			new PageContext.PS_ac_reciprocal(ele);
		},
		
		/*
		act_closeNewMessageWindow: function(ele) {
			newMessageArrived = new PageContext.newMessageArrived();
			ele.observe('click', function() {
				newMessageArrived.hideLayer();	
			});
			
			//ele.observe('click', newMessageArrived.hideLayer);
		},*/
		
		ps_messageForm: function (ele) {
			messageForm = new PageContext.PS_messageForm(ele);
		},
		
		ps_messageFormHelper: function (ele) {
			new PageContext.PS_messageFormHelper();
		},
		
		
		ps_printPage: function(ele) {
			new Helper.PS_printPage(ele);
		},

		ps_focusField: function (ele) {
			ele.focus();
		},
		
		ps_focusTextarea: function (ele, st, end) {
			setCursor(ele, 0, 0);
			ele.focus();

			function setCursor(ele, st, end) {
				if (ele.setSelectionRange) {
					ele.setSelectionRange(st, end);
				}
				else {
					if (ele.createTextrange) {
						range = ele.createTextrange();
						range.collapse(true);
						range.moveEnd(' ', end);
						range.moveStart(' ', st);
						range.select();
					}
				}
			}
		},
		
		ps_deleteMsgButton: function ps_deleteMsgButton(ele) {
			new PageContext.deleteOrRecoverMessages(ele);
		},
		ps_recoverMsgButton: function ps_recoverMsgButton(ele) {
			new PageContext.deleteOrRecoverMessages(ele);
		}
		
	},//end MethodMap
	
	/**
	 * @description Hands a MethodMap to Helper.applyClassHandlers
	 */
	initActionClasses: function initActionClasses() {
		Helper.applyClassHandlers(this.methodMap);
	},
	
	/**
	 * @description Other DOM inits e.g. Browsertweaks and DOMPrototypings 
	 */
	initOtherDomStuff: function initOtherDomStuff() {
		// fix scriptaculous Autocompleter iframe positioning at the end of page
		// in IE...assuming there are no "real" iframes with absolute
		// positioning!
		var iframeElems = $$('iframe');
		if (iframeElems) iframeElems.each(function (iframeElem) {
			if (iframeElem.style.position == 'absolute') iframeElem.setStyle({
				top: '-1000px'
			});
		});
		if(navigator.userAgent.indexOf('iPad') != -1) {  
			Par.Helper.loadCss('ipad');
		}  
				
		new Helper.domPrototyping();
	}
	
});


//********************************************************* Helper ***************************************************************
//********************************************************************************************************************************
/** @namespace Helper-Namspace for general Functions that can be used everywhere */
var Helper = {
		/**
		 * @class
		 * @description Hilfsfunktion. Durchläuft den gesamten Dokumentbaum und ruft für jedes
		 * @description Element, das eine Klasse hat, die in der methodMap vorkommt, den
		 * @description entsprechenden Handler auf.
		 */
		applyClassHandlers : function applyClassHandlers(methodMap, elementsSubset) {
			if(!elementsSubset) {
				var allElements = Element.descendants(document.body);
			} else {
				var allElements = Element.descendants($(elementsSubset));
			}
			var aLength = allElements.length;
			for (var i = 0; i < aLength; i++) {
				var q = new Date().getTime();
				var element = allElements[i];
				var classes = element.className.split(" ");
				var length = classes.length;
				for (var j = 0; j < length; j++) {
					var method = methodMap[classes[j]];
					if (method) {
						try {
							method($(element));
						} catch (e) {
							PS.debug(e);
						}
					}
				}
			}
			PS.debug("FINISHED: initActionClasses");
		},
		
		getImageJsonUrl: function getImageJsonUrl(imageJsonUrl, imageOwnerId, imagesize, imageNumber, callback) {
			new Ajax.Request(imageJsonUrl + '?rand=' + Helper.getAntiCache(), {
				method: 'post',
				parameters: {
					"imageOwnerId": imageOwnerId,
					"imageSize": imagesize,
					"imageNumber": imageNumber
				},
				onSuccess: function (transport) {
					callback(transport);
				}
				
			});
		},
		
		
		domPrototyping : Class.create({
			initialize: function initialize() {
				/**
				 * Prototypes String-Objects for a function that removes Whitespaces
				 * @return {String} trimed String
				 * */
				String.prototype.trim = function () {
					return (this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
				};
			}
		}),
		
		
				
	/** @class
	 * @description enhances scriptaculous Effect.ScrollTo so that scrolling can stop at a chosen margin above the element */ 
	PS_scrollTo : Class.create(
		/** @lends Helper.PS_scrollTo */
		{
		initialize: function initialize(ele, margin, alignBottom) {
			if (ele == undefined) return false;
			// special case: scroll to align bottom border of element at viewport bottom
			if (alignBottom) margin = document.viewport.getHeight() - ele.getHeight() - margin;
			var oldPos = ele.getStyle('position');
			var oldTop = ele.getStyle('top');
			var oldPaddingTop = ele.getStyle('paddingTop');
			ele.setStyle({
				position: 'relative',
				top: -margin + 'px',
				paddingTop: margin + 'px'
			});
			new Effect.ScrollTo(ele, {duration: '0.2'});
			ele.setStyle({
				position: oldPos,
				top: oldTop,
				paddingTop: oldPaddingTop
			});
		}
	}),
	
	/** @class
	 * @description Simply calls the Browsers print()-Function. 
	 */ 
	PS_printPage : Class.create(
		/** @lends Helper.PS_printPage */
		{
		initialize: function initialize(ele) {
			//new Helper.disableHref(ele);
			ele.observe('click', this.openPrintDialog.bindAsEventListener(this));
		},
		
		openPrintDialog: function openPrintDialog() {
			window.print();
		}
	}),
	
	/**
	 * @class
	 * 
	 * Inline labels for &lt;input&gt; elements
	 * 
	 * @description Adds inline default values for input texts and password fields default values
	 * @description are parsed from labels attached to input fields
	 */
	PS_inputDefault : Class.create(
		/** @lends Helper.PS_inputDefault */
		{
		/**
		 * @param {String} ele DOM id of an input element
		 */
		initialize: function initialize(ele) {
			this.ele = $(ele);
			this.fieldLabel = $(this.ele.id + '_label');
			this.fieldType = this.ele.readAttribute('type');
			this.defaultValue = '';

			if (this.fieldType == 'password') {
				this.fakeField = $(this.ele.id + '_fakefield');
				this.fakeField.value = this.fakeField.value.gsub(/\s*:\s*$/, "");
				// check for auto fill!!
				if (this.ele.value) {
					this.fakeField.hide();
					this.ele.setStyle('display:inline');
					this.ele.focus();
				}
				Event.observe(this.fakeField, 'focus', this.focus.bindAsEventListener(this));
				Event.observe(this.ele, 'blur', this.blur.bindAsEventListener(this));
			}
			else {
				if (this.fieldLabel) {
					if(this.ele.value == "") {this.ele.addClassName('ps_defaultValueClass');}
					this.defaultValue = this.fieldLabel.innerHTML.gsub(/\s*:\s*$/, "");
				}
				// check for auto fill!!
				if (!this.ele.value) {
					this.ele.value = this.defaultValue;
				}
				Event.observe(this.ele, 'focus', this.focus.bindAsEventListener(this));
				Event.observe(this.ele, 'blur', this.blur.bindAsEventListener(this));
			}
		},

		/**
		 * @description Event handler
		 * @private 
		 */
		focus: function () {
			if (this.fieldType == 'password') {
				this.fakeField.hide();
				this.ele.setStyle('display:inline');
				this.ele.focus();
				Event.stopObserving(this.fakeField, 'focus', this.focus.bindAsEventListener(this));
			} else {
				if (this.ele.value.trim() == this.defaultValue.trim()) {
					var agent = navigator.userAgent.toLowerCase();
					if (this.ele.id == "ps_partnerNoteTextarea" && agent.indexOf("firefox/3.6".toLowerCase())>-1) {  
						//damn we have to this here. Otherwise the new partnerNote Field will fail with Events sometimes...
					} else {
						this.ele.value = "";
					}
				}
				this.ele.removeClassName("ps_defaultValueClass");
			}
		},
		
		/**
		 * @description Event handler
		 * @private 
		 */
		blur: function () {
			if (this.ele.value == '') {
				if (this.fieldType == 'password') {
					this.fakeField.show();
					this.ele.setStyle('display:none');
				}
				else {
					this.ele.addClassName("ps_defaultValueClass");
					this.ele.value = this.defaultValue;
				}
			}
		},
		
		/**
		 * @description Helps to avoid accidental submits of label values
		 * 				as user input
		 * @param {String} DOMElement for form
		 */
		clearDefaultValuesBeforeSubmit : function clearDefaultValuesBeforeSubmit(form) {
			if(form != null) {
				this.form = form;
				$(this.form).select('.ps_inputDefault').each(function(fields){
					fieldId = fields.id;
					theDefaultText = $(fieldId + "_label");
					if(fields.value == theDefaultText.innerHTML.gsub(/\s*:\s*$/, "")) { //":" will be striped by inputDefault-Function
						fields.value = "";
					}
				});
			}
		},
		
		/**
		 * @description Used to restore inline labels after they have
		 * 				been removed for a form submit
		 * @param {String} DOMElement for form
		 */
		fillDefaultValuesAfterSubmit : function fillDefaultValuesAfterSubmit(form) {
			if(form != null) {
				this.form = form;		
				$(this.form).select('.ps_inputDefault').each(function(fields){
					fieldId = fields.id;
					theDefaultText = $(fieldId + "_label");
					if(fields.value == "") { //":" will be striped by inputDefault-Function
						fields.value = theDefaultText.innerHTML.gsub(/\s*:\s*$/, "");
					}
				});
			}
		}
		
	}),
	

	/**
	 * @class
	 * @description Open a new Window-popup (only on profiledelete used)
	 * */
	//var PS_popup;
	PS_popupHandler : Class.create(
		/** @lends Helper.PS_popupHandler */
		{
		/** 
		 * @description CSS trigger class: ps_pop
		 * @param {Object} ele An element to be used as the trigger button
		 */
		initialize: function initialize(ele) {
			this.ele = ele;
			this.width = this.getPopWidth();
			this.height = this.getPopHeight();
			this.ele.observe('click', this.open.bindAsEventListener(this));

			if (this.ele.hasClassName('ps_pop_auto')) {
				this.ele.observe('ps:pop_auto', this.open.bindAsEventListener(this));
				this.ele.fire("ps:pop_auto");
			}
		},

		/**
		 * @private
		 * @returns {Int} The width the popup should be set to
		 */
		getPopWidth: function getPopWidth() {
			value = 600;
			if (this.ele.className) {
				this.ele.className.split(" ").each(function (v) {
					if (v.match(/^ps_pop_\d+_\d+$/)) {
						value = v.gsub(/^ps_pop_(\d+)_\d+/, '#{1}');
					}
				});
			}
			return value;
		},

		/**
		 * @private
		 * @returns {Int} The height the popup should be set to
		 */
		getPopHeight: function getPopHeight() {
			value = 500;
			if (this.ele.className) {
				this.ele.className.split(" ").each(function (v) {
					if (v.match(/^ps_pop_\d+_\d+$/)) {
						value = v.gsub(/^ps_pop_\d+_(\d+)/, '#{1}');
					}
				});
			}
			return value;
		},
		/**
		 * @private
		 * @description Event handler for 'click'
		 * @param {DOMEvent} evt 
		 */
		open: function open(evt) {
			params = "width=" + this.width + ",height=" + this.height + ",resizable=1,scrollbars=1";
			//if (PS_popup != undefined) PS_popup.close();
			PS_popup = window.open(evt.element().href, "ps_popup", params);
			if (PS_popup) PS_popup.focus();
			evt.stop();
		}
	}),
	
	
	/**
	 * @class
	 * Binds a character counter to an &lt;input&GT; or &lt;textarea&gt;
	 */
	PS_inputObserver : Class.create(
		/** @lends Helper.PS_inputObserver */	
		{
		/**
		 * @description CSS trigger class: 		ps_charLimit
		 * 				CSS parameter class:	ps_max_&lt;number&gt; maximum character count
		 * 				Secondary targets:		#&lt;main_object ID&gt;_message will be shown when the character count is reached, and hidden when the count decreases.
		 *  
		 * 				
		 * 
		 * @param {Object} ele &lt;input&gt; element to be observed
		 */
		initialize: function v(ele) {
			this.ele = ele;
			this.id = ele.id;
			this.max = this.getMax();
			this.observe();
		},
		
		/**
		 * @private
		 */
		observe: function observe() {
			this.ele.observe('click', this.updateCount.bindAsEventListener(this));
			this.ele.observe('keydown', this.updateCount.bindAsEventListener(this));
			this.ele.observe('keyup', this.updateCount.bindAsEventListener(this));
			this.ele.observe('change', this.updateCount.bindAsEventListener(this));
			this.ele.observe('focus', this.updateCount.bindAsEventListener(this));
			this.ele.observe('blur', this.updateCount.bindAsEventListener(this));
			this.ele.observe('ps:inputobserver_init', this.updateCount.bindAsEventListener(this));
			this.ele.fire("ps:inputobserver_init");
		},
		
		/** 
		 * @private
		 * @description Defaults to 10.000; looks for a CSS parameter class in form
		 * 				of ps_max_&lt;number&gt;
		 * @return {int} maxLength value for current input/textarea
		 */
		getMax: function getMax() {
			count = "10000";
			if (this.ele.className) {
				this.ele.className.split(" ").each(function (c) {
					if (c.match(/^ps_max_\d+$/)) {
						count = c.replace('ps_max_', '');
					}
				});
			}
			return count;
		},

		/** 
		 * @private
		 * @description Event handler for ps:inputobserver_init
		 * 				Responsible for updating the character counter, limit notification and
		 * 				growing &lt;textarea&gt;s
		 */
		updateCount: function updateCount() {
			if ($(this.id)) {
				var counterElem = $(this.id + "_counter");
				var word = $F(this.id);
				var count = 0;
				if (word) count = word.length;
				if (count >= this.max) {
					if (count > this.max) {
						var truncValue = word.truncate(this.max, '');
						this.ele.value = truncValue;
						count = truncValue.length;
					}
					if (counterElem) {
						counterElem.up().addClassName('ps_inputLimitReached');
					}
				}
				else {
					if (counterElem) counterElem.up().removeClassName('ps_inputLimitReached');
				}

				if (counterElem) counterElem.update(count);

				if (this.ele.hasClassName("ps_expand")) {
					if (this.scrollHeight > this.getHeight()) this.rows += 1;
				}

				// Show message for length limit
				var messageElem = $(this.id + "_message");
				if (messageElem) {
					if (count >= this.max) {
						messageElem.show();
					}
					else {
						$(this.id + "_message").hide();
					}
				}
			}
		}
	}),
	
	
	/** 
	 * @class
	 * @description Creates our standard Tooltips ("Following the Mouse" and "Static" Ones)
	 * @deprecated todo: try to replace with any standard lib // remove dropdownOptionChoose
	 * */ 
	PS_tooltip : Class.create(
		/** @lends Helper.PS_tooltip */	
		{
		initialize: function initialize(ele) {
			if (!ele.id) {
				ele.identify();
				if (!ele.next()) {
					ele.up().next().addClassName(ele.id);
				} else {
					ele.next().addClassName(ele.id);
				}
			}

			// get tooltip to treat
			this.ele = $(ele);
			this.tooltip = $$("." + this.ele.id)[0];

			if (!this.tooltip) return;
			this.w = this.getWidth(this.tooltip);
			if (!this.tooltip) return;
			//this.tooltip.show();

			// create tooltip area layer if it's not already present
			if (!$('ps_tooltipAreaWrapper')) {
				var tooltipArea = new Element('div', {
					'id': 'ps_tooltipAreaWrapper',
					'class': 'parship'
				});
				Element.insert($('parship'), {
					'after': tooltipArea
				});
				Element.insert($('ps_tooltipAreaWrapper'), new Element('div', {
					'id': 'ps_tooltip_arrow'
				}));
			}

			// wrap in necessary elements
			var tempElem = this.tooltip.wrap('div', {
				'class': 'ps_tooltip_body'
			});
			var dialogElem = tempElem.wrap('div', {
				'class': 'ps_tooltip_dialog ' + this.tooltip.className
			});
			dialogElem.removeClassName(this.ele.id);
			

			var wrapperStyle = (this.w ? ' width: ' + this.w + 'px;' : ' white-space: nowrap;');
			dialogElem.wrap('div', {
				'class': this.ele.id + ' ps_tooltipWrapper',
				'style': wrapperStyle
			});


			// unhide tooltip content area (previously hidden to prevent flickering)
			this.tooltip.show();
			$(this.tooltip).removeClassName("ps_fullOpacity");

			// get newly wrapped tooltip and move it to tooltip area layer
			this.tooltip = $$("." + this.ele.id)[0];
			Element.insert($('ps_tooltipAreaWrapper'), Element.remove(this.tooltip));

			Event.observe(this.ele, "mouseover", this.inside.bindAsEventListener(this));
			Event.observe(this.ele, "mousemove", this.inside.bindAsEventListener(this));
			Event.observe(this.ele, "mouseout", this.outside.bindAsEventListener(this));
		},
		
		inside: function inside(evt) {
			if($(this.ele).hasClassName("ps_tooltipDisabled")) {
				//nothing
			} else {
				this.tooltip.show();
				$(this.tooltip).addClassName("ps_fullOpacity");
				$('ps_tooltip_arrow').show();
				x = Event.pointerX(evt);
				y = Event.pointerY(evt) - Element.getDimensions(this.tooltip).height - 6;
				scrollX = document.viewport.getScrollOffsets()[0];
				scrollY = document.viewport.getScrollOffsets()[1];
				viewportX = document.viewport.getWidth();
				arrowClass = "ps_arrowNorth";
	
				if (this.ele.hasClassName('ps_tooltipBelow')) {
					arrow = "s";
					x = this.ele.cumulativeOffset()[0] + 34;
					y = this.ele.cumulativeOffset()[1] + 98;
	
					arrowX = this.ele.cumulativeOffset()[0] + 28;
					arrowY = this.ele.cumulativeOffset()[1] + 90;
					arrowClass = "ps_arrowSouth";
				}
				else if (this.ele.hasClassName('ps_myStatusHeadPhoto')) {
					arrow = "s";
					x = this.ele.cumulativeOffset()[0] + 19;
					y = this.ele.cumulativeOffset()[1] + 54;
	
					arrowX = this.ele.cumulativeOffset()[0] + 13;
					arrowY = this.ele.cumulativeOffset()[1] + 46;
					arrowClass = "ps_arrowSouth";
				} else {
					arrow = "n";
					if (y - scrollY - 10 < 0) {
						arrow = "s";
						y = Event.pointerY(evt) + 20;
					}
					if (x + Element.getDimensions(this.tooltip).width > viewportX) {
						x = viewportX - Element.getDimensions(this.tooltip).width + 20;
					}
	
					if (arrow == "n") {
						arrowX = Event.pointerX(evt) - 5;
						arrowY = Event.pointerY(evt) - 11;
						arrowClass = "ps_arrowNorth";
					}
					else {
						arrowX = Event.pointerX(evt) - 8;
						arrowY = Event.pointerY(evt) + 12;
						arrowClass = "ps_arrowSouth";
					}
	
				}
				$('ps_tooltip_arrow').addClassName(arrowClass);
	
				$('ps_tooltip_arrow').setStyle({
					top: arrowY + "px",
					left: arrowX + "px"
				});
	
				widthValue = this.w ? this.w : this.tooltip.getWidth();
				Element.setStyle(this.tooltip, {
					width: widthValue,
					top: (y + 5) + "px",
					left: x + "px"
				});
			}
		},

		outside: function outside(evt) {
			if($(this.ele).hasClassName("ps_tooltipDisabled")) {
				//nothing
			} else {
				//this.tooltip.hide();
				$(this.tooltip).removeClassName("ps_fullOpacity");
				$('ps_tooltip_arrow').hide();
			}
		},

		getWidth: function getWidth(elem) {
			var width;
			if (elem.className) {
				elem.className.split(" ").each(function (v) {
					if (v.match(/^ps_w\d+$/)) {
						width = v.gsub(/^ps_w(\d+)/, '#{1}');
					}
				});
			}
			return width;
		}
	}),
	
	/**
	 * @class
	 * @description Toggeling of Boxes via CSS-Classes 
	 * */
	PS_toggle : Class.create(
		/** @lends Helper.PS_toggle */	
		{
		initialize: function initialize(ele) {
			me = this;
			this.ele = $(ele);
			if (!this.ele.id) this.ele.identify();
			this.smooth = this.ele.hasClassName('ps_toggleSmooth');
			var c = this;
			var elem = $$('#' + this.ele.id + ' .ps_toggleHandle');
			if (elem) {
				elem.each(function (ele) {
					Event.observe(ele, "click", me.toggle.bindAsEventListener(c));
				});
			}

			elem = $$('#' + this.ele.id + ' .ps_toggleHandle_alt');
			if (elem) {
				elem.each(function (ele) {
					Event.observe(ele, "click", me.toggle.bindAsEventListener(c));
				});
			}

			//Icon to show up or down
			elem = $$('#' + this.ele.id + ' .ps_toggleHandleIcon');
			if (elem) {
				elem.each(function (ele) {
					var visible = c.getToggleAreaVisibility(ele);
					ele.setStyle({
						backgroundImage: "url(/static/redesign09/img/bg_toggleHandle_" + visible + ".gif)"
					});
					Event.observe(ele, "click", me.toggle.bindAsEventListener(c));
				});
			}
		},
		/** Do the Toggeling (switching visibility) */
		toggle: function toggle(evt) {
			evt.stop();
			var t = this;
			var toggleParentElem = evt.element().up('.ps_toggle');

			toggleAreas = toggleParentElem.select('.ps_toggleArea');
			if (toggleAreas.length == 0) {
				toggleAreas = new Array();
				toggleAreas.push($('ps_toggleArea_' + toggleParentElem.id));
			}
			if (toggleAreas && toggleAreas.length > 0) toggleAreas.each(function (ele) {
				ele.toggle();
			});

			var toggleHandles = toggleParentElem.select('.ps_toggleHandle');
			var toggleHandlesAlt = toggleParentElem.select('.ps_toggleHandle_alt');
			if (toggleHandles.length > 0 && toggleHandlesAlt.length > 0) {
				toggleHandles.each(function (ele) {
					ele.toggle();
				});
				toggleHandlesAlt.each(function (ele) {
					ele.toggle();
				});
			}
			var toggleHandleIcons = toggleParentElem.select('.ps_toggleHandleIcon');
			if (toggleHandleIcons.length > 0) {
				var c = this;
				toggleHandleIcons.each(function (ele) {
					var visible = c.getToggleAreaVisibility(ele);
					ele.setStyle({
						backgroundImage: "url(/static/redesign09/img/bg_toggleHandle_" + visible + ".gif)"
					});
				});
			}
		},
		
		getToggleAreaVisibility: function getToggleAreaVisibility(ele) {
			var toggleArea = null;
			var toggleAreaIn = ele.up('.ps_toggle').down('.ps_toggleArea');
			var visible = "off";
			if (toggleAreaIn) {
				toggleArea = toggleAreaIn;
			}
			else {
				var toggleAreaOut = $('ps_toggleArea_' + ele.up('.ps_toggle').id);
				if (toggleAreaOut) {
					toggleArea = toggleAreaOut;
				}
			}
			if (toggleArea) {
				visible = toggleArea.visible() ? "off" : "on";
			}
			return visible;
		}

		
	}),
	
	
	/*
	 * @class
	 * @description Dependant Dropdowns - if you choose something on min-box the max-box will be affected
	 */
	PS_dropdownDependency : Class.create(
		/** @lends Helper.PS_dropdownDependency */	
		{
		initialize: function initialize(min, max, minVals, minTexts, maxVals, maxTexts) {
			this.minDropdown = $(min);
			this.maxDropdown = $(max);

			this.minVals = $A(minVals);
			this.maxVals = $A(maxVals);

			this.minTexts = $A(minTexts);
			this.maxTexts = $A(maxTexts);

			this.minSelected = this.minDropdown.options[this.minDropdown.selectedIndex];
			this.maxSelected = this.maxDropdown.options[this.maxDropdown.selectedIndex];

			// somewhat of a hack, but _should_ contain the value that has attr
			// selected=selected
			// on initialisation. saving this allows us to preserve the selected
			// attr when calling refillMax,
			// so that form resets work correctly
			this.maxDefaultValue = this.maxSelected.value;

			this.dontCareOptionText = "x";

			Event.observe(this.minDropdown, "change", this.minChanged.bindAsEventListener(this, this.minDropdown));
			Event.observe(this.maxDropdown, "change", this.maxChanged.bindAsEventListener(this, this.maxDropdown));
		},
		
		/** Text for very first Option "I don't care" */
		setDontCareOptionText: function setDontCareOptionText(text) {
			this.dontCareOptionText = text;
		},

		minChanged: function v(ev, ele) {
			this.minSelected = ele.options[ele.selectedIndex];
			allNumbers = !isNaN(this.minSelected.value) && !isNaN(this.maxSelected.value);
			for (i = 0; i < this.minDropdown.options.length; i++) {
				if (this.minDropdown.options[i].value == "0") {
					this.minDropdown.options[i].text = this.dontCareOptionText;
				}
			}
			PS.debug("this.minSelected.value: " + parseInt(this.minSelected.value));
			PS.debug("this.maxSelected.value: " + parseInt(this.maxSelected.value));
			if (allNumbers && parseInt(this.minSelected.value) >= parseInt(this.maxSelected.value)) {
				PS.debug("min gr max");
				this.refillMax();
				// get actual maxsize - search in array for next higher value
				actSelectedValIndex = this.maxVals.indexOf(parseInt(this.maxSelected.value));
				newMaxValToSelect = this.maxVals[actSelectedValIndex - 1];
				// PS.debug(this.maxDropdown.options[this.maxDropdown.selectedIndex].value);
				if (this.maxSelected.value == "0" || this.maxDropdown.options[this.maxDropdown.selectedIndex].value == "0") {
					newMaxValToSelect = "0";
				}
				for (i = 0; i < this.maxDropdown.options.length; i++) {
					if (this.maxDropdown.options[i].value == newMaxValToSelect) {
						PS.debug("this.maxDropdown.options[i].value: " + this.maxDropdown.options[i].value);
						PS.debug("newMaxValToSelect: " + newMaxValToSelect);
						this.maxDropdown.options[i].selected = true;
						return;
					}
				}
			}
			else if (allNumbers && parseInt(this.minSelected.value) < parseInt(this.maxSelected.value)) {
				PS.debug("min kleiner max");
				// refill maxfield
				var oldMaxVal = this.maxSelected.value;
				this.refillMax();
				this.maxSelected.value = oldMaxVal;
				for (i = 0; i < this.maxDropdown.options.length; i++) {
					if (this.maxDropdown.options[i].value == this.maxSelected.value) {
						this.maxDropdown.options[i].selected = true;
						return;
					}
				}
				// } else if(allNumbers && this.maxSelected.value == "0") {
			}
		},
		maxChanged: function maxChanged(ev, ele) {
			this.maxSelected.value = ele.options[ele.selectedIndex].value;
		},

		refillMax: function refillMax() {
			PS.debug("refillMax");
			this.removeAllOption(this.maxDropdown);
			for (i = 0; i < this.maxVals.length; i++) {
				if (this.maxVals[i] > this.minSelected.value) {
					// was this option originally selected=selected?
					if (this.maxVals[i] == this.maxDefaultValue) {
						var makeDefaultSelected = true;
					}
					else {
						var makeDefaultSelected = false;
					}
					this.addOption(this.maxDropdown, this.maxTexts[i], this.maxVals[i], false, makeDefaultSelected);
				}

				if (this.maxVals[i] == this.minSelected.value) {
					if (this.maxSelected.value != "0") {
						PS.debug("this.maxVals[i] == this.minSelected.value");
						this.maxSelected.value = this.minSelected.value;
					}
				}
			}
			
			if (this.dontCareOptionText != "") { // append "egal" Option as last
				// Value
				this.addOption(this.maxDropdown, this.dontCareOptionText, '0', false, false);
			}
		},

		addOption: function addOption(selectObj, text, value, isSelected, defaultSelected) {
			if (selectObj != null && selectObj.options != null) {
				selectObj.options[selectObj.options.length] = new Option(text, value, defaultSelected, isSelected);
			}
		},
		removeAllOption: function removeAllOption(selectObj) {
			if (selectObj != null && selectObj.options != null) {
				selectObj.options.length = 0;
			}
		}

	}),
	
	
	/**
	 * @description Stops the linkEvent on a href. -> Makes a link stop working but affects no style
	 */
	disableHref: Class.create(
		/** @lends Helper.disableHref */	
		{
		initialize: function initialize(elem) {
			elem.setAttribute('onclick', 'return false;'); //FF
			elem.onclick = function(){ //IE!
				return false;
			};
			elem.setAttribute('target', '');
			elem.tempHref = elem.href;
			elem.href = "javascript:void(0);";
			return this;
		}
	}),
	
	/**
	 * @class
	 * @description Can make a Button appear disabled */
	PS_buttonDisable : Class.create(
		/** @lends Helper.PS_buttonDisable */	
		{
		initialize: function initialize(btnEle, clickEles) {
			this.btnEle = btnEle;
			var c = this;
			if (clickEles) {
				clickEles.each(function (e) {
					Event.observe(e, 'click', c.click.bindAsEventListener(c));
				});
			}
			this.disableBtn();
		},
		click: function click() {
			this.enableBtn();
		},
		disableBtn: function disableBtn() {
			//this.btnEle.setOpacity(0.3);
			/*this.btnEle.setStyle({
				cursor: 'default'
			});*/
			this.btnEle.addClassName("disabledButton");
			this.btnEle.observe("click", function(ev) {
				Event.stop(ev);
			})
			
		},
		enableBtn: function enableBtn() {
			//this.btnEle.setOpacity(1);
			/*this.btnEle.setStyle({
				cursor: 'pointer'
			});*/
			this.btnEle.removeClassName("disabledButton");
			this.btnEle.onclick = null;
		}
	}),
	
	/**
	 * @class
	 * @description Disable a Form submit (including Cursor and Style) */
	PS_disableOnSubmit : Class.create(
		/** @lends Helper.PS_disableOnSubmit */	
		{
		initialize: function initialize(btnEle) {
			this.btnEle = btnEle;
			Event.observe(btnEle, 'click', this.disableBtn.bindAsEventListener(this));
		},

		disableBtn: function disableBtn() {
			this.btnEle.disabled = true;
			this.btnEle.setOpacity(0.3);
			this.btnEle.setStyle({
				cursor: 'default'
			});
			this.btnEle.onclick = function () {
				return false;
			};
		}
	}),
	
	/**
	 * @class
	 * @description Needed to put the selected Filename into our Fake-Inputfield for input-type=file */
	PS_fakeInput : Class.create(
		/** @lends Helper.PS_fakeInput */	
		{
		initialize: function initialize() {
			var ele = $$('input[type="file"]')[0];
			if (ele) {
				PS.debug("init PS_fakeInput: id=" + ele.id);

				this.uploadBtn = $('ps_uploadBtn');
				if (this.uploadBtn) this.disableUploadBtn();
				// this.isClicked = true;
				var prefix = 'ps_fakeInputTarget_';
				var c = this;
				ele.classNames().each(function (cn) {
					if (cn.startsWith(prefix)) {
						c.fakeInputId = cn.substring(prefix.length, cn.length);
					}
				});
				if (this.fakeInputId) {
					// Event.observe(ele, 'click',
					// this.click.bindAsEventListener(this));
					Event.observe(ele, 'mouseout', this.outside.bindAsEventListener(this));
					Event.observe(ele, 'mouseover', this.inside.bindAsEventListener(this));
					Event.observe(ele, 'change', this.outside.bindAsEventListener(this));
				}

			}
		},
		click: function click() {
			// this.isClicked = true;
		},
		inside: function inside() {
			// $('ps_field_fakeUploadCtrl').src='/static/img/_locales/' +
			// $('ps_field_fakeUploadCtrl').lang + '/btn_uploadimg_hover.gif';
		},
		outside: function outside(ev) {
			// if (this.isClicked) {
			$(this.fakeInputId).value = ev.element().value;
			if ($(this.fakeInputId).value == '') {
				if (this.uploadBtn) this.disableUploadBtn();
			}
			else {
				if (this.uploadBtn) this.enableUploadBtn();
			}
			// this.isClicked = false;
			// }
		},
		disableUploadBtn: function disableUploadBtn() {
			this.uploadBtn.addClassName('ps_uploadDisabled');
			this.uploadBtn.onclick = function () {
				return false;
			};
		},
		enableUploadBtn: function enableUploadBtn() {
			this.uploadBtn.removeClassName('ps_uploadDisabled');
			this.uploadBtn.onclick = null;
		}
	}),
	
	/**
	 * @description returns Timestamp to put into a json submit URL, so the browser does not deliver a cached Version */
	getAntiCache: function getAntiCache() {
		return new Date().getTime();
	},

	/**
	 * @description Make a Pause for given milliseconds in Execution */
	pauseExec : function pauseExec(millis) {
		var date = new Date();
		var curDate = null;
		do { curDate = new Date(); } 
		while(curDate-date < millis);
	},
	
	
	/**
	 * @description Manipulates the color of an Image by Factor 
	 * returns a bas64 src */
	manipulateImageColor: function manipulateImageColor(src, factor) {
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var imgObj = new Image();
		imgObj.src = src;

		canvas.width = imgObj.width;
		canvas.height = imgObj.height; 
		ctx.drawImage(imgObj, 0, 0); 
		
		var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
		for(var y = 0; y < imgPixels.height; y++){
			for(var x = 0; x < imgPixels.width; x++){
				var i = (y * 4) * imgPixels.width + x * 4;
				var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
				imgPixels.data[i] = imgPixels.data[i] - factor; 
				imgPixels.data[i + 1] = imgPixels.data[i + 1] - factor; 
				imgPixels.data[i + 2] = imgPixels.data[i + 2] - factor;
			}
		}
		ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
		return canvas.toDataURL();
    },
	
	
	updateTextareSize: Class.create({
	  initialize: function( element, options ) {
	    element = $( element );
	    this.element = element;
	    this.options = Object.extend(
	      {},
	      options || {} );

	    Event.observe( this.element, 'keyup',
	      this.onKeyUp.bindAsEventListener( this ) );
	    this.onKeyUp();
	  },
	  onKeyUp: function() {
	    // We need this variable because "this" changes in the scope of the
	    // function below.
	    var cols = this.element.cols;
	    var linecount = 0;
	    $A( this.element.value.split( "\n" ) ).each( function( l ) {
	      // We take long lines into account via the cols divide.
	      linecount += 1 + Math.floor( l.length / cols );
	    } )
	    if(linecount <= 1) linecount = 2;//minimum 2 rows
	    this.element.rows = linecount;
	  }
	}),
	
	
	/**
	 * @class
	 * @description Jump to first Error on Page and hide ErrorMessage on Top of Page 
	 */
	PS_hasError : Class.create(
		/** @lends Helper.PS_hasError */	
		{
		initialize: function initialize(elem) {
			$$('.ps_errorHeadline')[0].hide();
			new Helper.PS_scrollTo($$('.ps_hasError')[0], 20);
		}
	}),
	
	/*Wieder einkommentierne, sobald messagepolling wieder aktiviert wird
	 * act_ajaxUpdater : Class.create(*/
		/** @lends Helper.act_ajaxUpdater */	
		/*{
			initialize: function initialize(elem) {
				updaterInterval = pageVars.updaterInterval * 1000; 
				updaterUrl = pageVars.updaterUrl+"?rand=";
				myPeriodicalUpdate = this.periodicalUpdate;
				myStopUpdater = this.stopUpdater;
				updater = window.setInterval("myPeriodicalUpdate()", updaterInterval);
				myStopUpdater();
			}, 
			
			periodicalUpdate: function periodicalUpdate() {
				new Ajax.Request(updaterUrl + Helper.getAntiCache(), {
					method: 'get',
					onSuccess: function () { // Invoked when a request completes and its status code is undefined or belongs in the 2xy family.
						this.hasSuccess = true;
					},
					onComplete: function (transport) { // Triggered at the very end of a request's life-cycle, once the request completed
						if (this.hasSuccess == true) {
							transport = transport.responseText.evalJSON();
							if(transport.newMessage) {
								//newMessageArrived = new PageContext.newMessageArrived();
								newMessageArrived.showLayer();
								//newMessageArrived.hideLayer();
							}
						}
					}
				});
				
			},
			stopUpdater: function periodicalUpdate() {
				//check if timer should be stopped
				if(pageVars.stopUpdateInterval != undefined) {
					window.clearInterval(updater);
				}
			}
	}),
	*/
	
	
	/**
	 * @class
	 * @description Logic for "Check all Checkboxes". (Basiccriteriapage / Messagedeletion)
	 * */
	checkboxChecker : Class.create(
		/** @lends Helper.checkboxChecker */
		{
		initialize: function() {

		},
		
		checkAllInput: function(elem) {
			this.elem = elem;		
			this.elem.observe('click', this._clickCheckAllInput.bind(this));
			this._checkstatus(this);
		},
		
		_clickCheckAllInput: function(ev) {
			this.wrapperClass = this.elem.up('.ps_checker').next('.ps_allSingleCheckboxes');
			if (this.elem.checked) {
				this._checkall(this.wrapperClass);
			} else {
				this._uncheckall(this.wrapperClass);
			}
		},
		
		_checkall: function(elem) {
			elem.descendants().each(function(v) {
				if(v.down('input[type=checkbox]') != null) {
					v.down('input[type=checkbox]').checked = true;
				}
			});
		},
		
		_uncheckall: function(elem) {
			elem.descendants().each(function(v) {
				if(v.down('input[type=checkbox]') != null) {
					v.down('input[type=checkbox]').checked = false;
				}
			});
		},
		
		//Has any region been unchecked - uncheck ALL-checkbox
		_checkstatus: function(elem) {
			this.elem.checked = true;
			this.elem.up('.ps_checker').next('.ps_allSingleCheckboxes').descendants().each(function(v) {
				if (v.down('input[type=checkbox]') != null && v.down('input[type=checkbox]').checked == false){
					v.up('.ps_allSingleCheckboxes').previous('.ps_checker').down('.ps_checkerCheckbox').checked = false;
				}
			});
		},
	
		
		//clicks on singleCheckbox
		singleCheckbox: function (elem) {
			this.elem = elem;		
			this.elem.observe('click', this._clickSingleCheckbox.bind(this));
		},
		_clickSingleCheckbox: function(ev) {
			/*set CheckAllInput to unchecked */
			if (!this.elem.checked) {
				this.elem.up('.ps_allSingleCheckboxes').previous('.ps_checker').down('.ps_checkerCheckbox').checked = false;
			}
			
			/*set checkAllInput to checked if all regions selected */
			setChecked = true;
			this.elem.up('.ps_allSingleCheckboxes').descendants().each(function(v) {
				if (v.down('input[type=checkbox]') != null && v.down('input[type=checkbox]').checked == false){
					setChecked = false;
				}
			});
			
			if (setChecked) {
				this.elem.up('.ps_allSingleCheckboxes').previous('.ps_checker').down('.ps_checkerCheckbox').checked = true;
			}

		},
		
		//Disable Region checkbox when submitting Searchcriteria Form
		disableCheckAllInput : function(elem) {
			this.elem = elem;		
			this.elem.observe('click', this._clickDisableCheckAllInput.bind(this));
		},
		_clickDisableCheckAllInput: function(ev) {
			$$('.ps_checkerCheckbox').each(function(v){
				v.disable();
			});
		}
		
	}),
	
	/**
	 * @class
	 * @description Editieren und Speichern von:
	 * - AboutMe Fragen
	 *  - PersonalStatement
	 *  - (/settings/dataandsettings)   
	 **/
	saveAndEditQuestions : {
		init: function init () {
			myTransmissionInProgress = false;
			Helper.saveAndEditQuestions.savedValue = "";
		},
		
		editQuestion: function editQuestion(question, explicitCall, editCallback) {
			if(editCallback) editCallback();
			Helper.saveAndEditQuestions.savedValue = $(question).select('.ps_answerText')[0].innerHTML;
			if($('ps_aboutTabContent') && explicitCall) {//via User click on EditElement
				oldQuestion = "";
				if($('ps_aboutTabContent').getAttribute("data-currentOpenQuestion") != null) {
					oldQuestion = $('ps_aboutTabContent').getAttribute("data-currentOpenQuestion");
				}
				$('ps_aboutTabContent').setAttribute("data-currentOpenQuestion", question.id);
				if(oldQuestion != "") {
					Helper.saveAndEditQuestions.saveQuestion(null,  $(oldQuestion), false, Par.PageContext.editTabAboutMe.editQuestion); //implicit call here
				}
			} else {
				//PS.debug("autosave via Event Par:Inits:domInit:tabLoaded for: " + question);
				question = $(question);
			}
			
			
			$(question).select('.ps_questionDisplay .ps_answer')[0].addClassName("ps_notVisible");
			displaytextHeight = $(question).select('.ps_questionDisplay .ps_answer')[0].getHeight() + 20;
			$(question).select('.ps_questionEdit')[0].removeClassName("ps_inv");
			
			//Workaround to set the Cursor at the last Position of the Text (Its the easiest way... believe me)
			$(question).select('textarea')[0].focus();
			val = $(question).select('textarea')[0].value;
			$(question).select('textarea')[0].value = "";
			$(question).select('textarea')[0].value = val;
			
		},

		cancelQuestion: function cancelQuestion(ev, question, cancelCallback) {
			Helper.saveAndEditQuestions.savedValue = $(question).select('.ps_answerText')[0].innerHTML; 
			$(question).select('.ps_questionDisplay .ps_answer')[0].removeClassName("ps_notVisible");
			$(question).select('.ps_questionEdit')[0].addClassName("ps_inv");
			$(question).select('form')[0].reset();
			$(question).select('textarea')[0].value = Helper.saveAndEditQuestions.savedValue.gsub("<BR>", "\n").gsub("<br>", "\n"); //IE7 needs upperCase BR
			$(question).select('textarea')[0].setStyle({
				'height':'auto'
			})
			if($('ps_aboutTabContent')) $('ps_aboutTabContent').removeAttribute("data-currentOpenQuestion")
			if(cancelCallback) cancelCallback();
		},

		saveQuestion: function saveQuestion(ev, question, explicitSave, saveCallback) {
			_url = question.select('form')[0].action;
			question.select('.ps_indicator')[0].removeClassName("ps_inv");
			if($('ps_aboutTabContent') && explicitSave) {
				//PS.debug("explicitSave called");
				$('ps_aboutTabContent').removeAttribute("data-currentOpenQuestion");
			}
			if(myTransmissionInProgress) {
				//PS.debug("transmissionInProgress");
			} else {
				myTransmissionInProgress = true;
				new Ajax.Request(_url, {
					method: 'post',
					parameters: $(question).select("form")[0].serialize(),
					onSuccess: function (response) {
						result = response.responseText.evalJSON();
						if (result.resultView.success) {
							//Ich denke, es wäre schöbner, wenn wir hier den Tab einfach neu laden anstelle die logik hier doppelt vorzuhalten. Umbauen, wenn Zeit ist.
							if (result.resultView.displayText != "" || question.id == "ps_question_personalStat") {
								$(question).select('.ps_questionDisplay .ps_answer')[0].removeClassName("ps_notVisible");
								$(question).select('.ps_questionEdit')[0].addClassName("ps_inv");
								$(question).select('.ps_indicator')[0].addClassName("ps_inv");
								Helper.saveAndEditQuestions.savedValue = result.resultView.displayText;
								$(question).select('.ps_questionDisplay .ps_answer .ps_answerText')[0].innerHTML = result.resultView.displayText.gsub("\n", "<br />");
								if(result.resultView.approvalStatus == "AWAITING_APPROVAL") {
									$(question).select('.ps_notActivatedBox')[0].removeClassName("ps_inv");
								} else {
									$(question).select('.ps_notActivatedBox')[0].addClassName("ps_inv");
								}
							} else {
								$(question).remove();
							}
							Par.Helper.publishEvent("Par:PageContext:action:updateProfileCompletion", {});
						}
						myTransmissionInProgress = false;
						if(saveCallback) saveCallback();
						//if(explicitSave) {}
					},
					onFailure: function() {
						myTransmissionInProgress = false;
						question.select('.ps_indicator')[0].addClassName("ps_inv");
						question.select('.ps_error500')[0].removeClassName("ps_inv");
					}
				})
			}
			
		}
		
	}
	
	

	
};


////********************************************************* /Helper *************************************************************
//*************************************************************************************************************************************



/**
 * NEW Profile-Form-Validation Handling
 * should be generic to use for every Ajax-Call
 */
PS_ajaxForm = Class.create({
	initialize: function (submittedForm, ajaxPageLink, withApprovalBox, additionalParams, handleTransport) {
		mySubmittedForm = submittedForm; // an ID of that specific form that
		// should be submitted
		myWithApprovalBox = withApprovalBox;
		//myAjaxCompletedSuccess = this.ajaxCompletedSuccess;
		myHandleServerError = this.handleServerError;
		myHandleTransport = handleTransport;
		this.ajaxPageLink = ajaxPageLink + "?rand=" + Helper.getAntiCache(); // where to Submit - always set the timeStamp
		if(typeof allInputDefaults != "undefined") allInputDefaults.clearDefaultValuesBeforeSubmit(mySubmittedForm);
		this.formParams = $(mySubmittedForm).serialize();
		if (!additionalParams) this.additionalParams = ""; // parameters that
		// should be added to the request in the form ?param1=abc&param2=walla
		this.params = this.formParams + this.additionalParams;
		if (typeof this.params != "object") {
			this.params = this.params.toQueryParams();
		};

		this.submitMethod = "post";
		this.errorDiv = $('ajaxError'); // where to display errormessage
		// this.indicatorDiv = $('indicator'); //if we get an indicator for saving
		myDisplayValueReady = false;
		this.hasSuccess = false;
	},


	/**
	 * @classDescription The Ajax-Request itself.
	 */
	submitForm: function () {
		this.hasSuccess = false; // be pessimistic
		// params = removeDefaultValues(params); //Values prefilled in Textfields for example
		// ppAjax.showIndicator(replaceContainer);
		new Ajax.Request(this.ajaxPageLink, {
			method: this.submitMethod,
			parameters: this.params,
			onSuccess: function () { // Invoked when a request completes and its status code is undefined or belongs in the 2xy family.
				this.hasSuccess = true;
			},
			onComplete: function (transport) { // Triggered at the very end of a request's life-cycle, once the request completed
				if (this.hasSuccess == true) {
					eval(myHandleTransport)(mySubmittedForm, transport);
					// myAjaxCompletedSuccess(transport);
					if(!Object.isUndefined(allInputDefaults)) allInputDefaults.fillDefaultValuesAfterSubmit(mySubmittedForm);
				}
			},
			onFailure: myHandleServerError
		});
		// ppAjax.conf.indicatorDiv.removeClassName('inv');
	},

	/**
	 * Indicator-Layer anzeigen
	 */
	showIndicator: function (which) {
		// this.indicatorDiv.removeClassName('inv');
		// if ($$(which)[0] && $$(which)[0].select('.infoboxIndicator') &&
		// $$(which)[0].select('.infoboxIndicator')[0]) {
		// $$(which)[0].select('.infoboxIndicator')[0].removeClassName('inv');
		// }
	},

	/**
	 * Versteckt den Indicator-Layer
	 */
	hideIndicator: function (which) {
		// this.indicatorDiv.addClassName('inv');
		// /if ($$(which)[0] && $$(which)[0].select('.infoboxIndicator')) {
		// $$(which)[0].select('.infoboxIndicator')[0].addClassName('inv');
		// }
	},

	/**
	 * In case of 404/500 we could do something special here.
	 */
	handleServerError: function () {
		// nothing now
	}
});



//used for AB-Test / call injected via SO
function getCookie(cookieName){if(!document.cookie){return null;}var cookieStr=document.cookie;var cookies=cookieStr.split(";");for(i=0;i<cookies.length;i++){var cookie=cookies[i];var cookieKeyVal=cookie.split("=",2);if(cookieKeyVal[0].trim()==cookieName){return cookieKeyVal[1];}}return null;}
function setCookie(cookieName,cookieVal){var lifetime=null;var domain=null;var parameters;var arglength=2;if(typeof setCookie.arguments==="undefined"){parameters=arguments;}else{parameters=setCookie.arguments;}if(parameters.length>2){lifetime=parameters[2];}if(parameters.length>3){domain=parameters[3];}var cookieStr=cookieName+"="+cookieVal+"; path=/";if(lifetime!=null){var expires=lifetime;if(lifetime!=-1){var ablauf=new Date();ablauf.setTime(ablauf.getTime()+lifetime*1000);expires=ablauf.toGMTString();}cookieStr+="; expires="+expires;}if(domain!=null){cookieStr+="; domain="+domain;}document.cookie=cookieStr;}
function getMainDomain(fullDomain){var pattern=/^.*?((\.?[^.]+?)(\.([^.]+?)\.[^.]+?))$/;var result=pattern.exec(fullDomain);if(result){var secondleveldomainPart=result[4];var secondleveldomain=result[3];if(secondleveldomainPart=="co"||secondleveldomainPart=="com"){secondleveldomain=result[1];}return secondleveldomain;}return fullDomain;}

////********************************************************* PageContext *************************************************************
//*************************************************************************************************************************************
var PageContext = {
	 
	 //Sorry for nearly duplicating this Function
	 //Refactor
	 PS_bigImageGallery : Class.create({
			initialize: function (gallery) {
				isMoving = false;
				bigThat = this;
				bigThat.previewPics = gallery.select("li");
				bigThat.previewPicsCount = $A(bigThat.previewPics).length; //how much pics do we have

				if(bigThat.previewPicsCount > 0) {
					bigThat.previewPicWidth = 368; //width of a single pic incl margin
					bigThat.scrollWidth = bigThat.previewPicWidth; //scroll by 1 pictures
					
					bigThat.listToScroll = $$('.ps_imageFlowImages')[0];
					this.setArrowStatus('left', this.getScrollStatus('left'));
					this.setArrowStatus('right', this.getScrollStatus('right'));
	
					this.leftBtn = gallery.down('#ps_imageFlowLeftNavi');
					this.rightBtn = gallery.down('#ps_imageFlowRightNavi');

					Event.observe(this.leftBtn, 'click', this.leftClick.bindAsEventListener(this));
					Event.observe(this.rightBtn, 'click', this.rightClick.bindAsEventListener(this));
				}
			},
			
			getScrollStatus: function getScrollStatus(arrow) {
				if(arrow == "left") { 
					if(bigThat.listToScroll.positionedOffset().toArray().first() >= 0){
						return "disabled";
					} else {
						return "enabled";
					}
				} else {
					if (bigThat.listToScroll.positionedOffset().toArray().first() < -((bigThat.previewPicsCount-2) * bigThat.previewPicWidth)) {
						return "disabled";
					} else {
						return "enabled";
					}
				}
			},
			
			setArrowStatus: function setArrowStatus(arrow, status) {
				if(arrow == "left") {
					if(status == "disabled") {
						$('ps_imageFlowLeftNavi').addClassName("ps_disabled");
					} else {
						$('ps_imageFlowLeftNavi').removeClassName("ps_disabled");
					}
				} else {
					if(status == "disabled") {
						$('ps_imageFlowRightNavi').addClassName("ps_disabled");
					} else {
						$('ps_imageFlowRightNavi').removeClassName("ps_disabled");
					}
				}
			},
			
			leftClick: function() {
				if(this.getScrollStatus("left") == "enabled" && !isMoving) {
					isMoving = true;
					new Effect.Move(bigThat.listToScroll, {
		 				x: bigThat.scrollWidth,
		 				y: 0,
		 				duration: 0.3,
		 				queue: {
		 					scope: 'imageflow',
		 					limit: 1
		 				},
		 				afterFinish : function() {
		 					bigThat.setArrowStatus('left', bigThat.getScrollStatus('left'));	 					
		 					bigThat.setArrowStatus('right', bigThat.getScrollStatus('right'));
		 					isMoving = false; 
		 				}
		 			});	
				}
				
			},
			
			rightClick: function() {
				if(this.getScrollStatus("right") == "enabled" && !isMoving) {
					isMoving = true;
					new Effect.Move(bigThat.listToScroll, {
		 				x: -bigThat.scrollWidth,
		 				y: 0,
		 				duration: 0.3,
		 				queue: {
		 					scope: 'imageflow',
		 					limit: 2
		 				},
		 				afterFinish : function() {
		 					bigThat.setArrowStatus('right', bigThat.getScrollStatus('right'));
		 					bigThat.setArrowStatus('left', bigThat.getScrollStatus('left'));
		 					isMoving = false; 
		 				}
		 			});
				}
				
			},
			
			showGalleryImage: function (galleryImgNum) {
		 		var pos = galleryImgNum * -bigThat.previewPicWidth;
		 		bigThat.listToScroll.setStyle({
		 			left: pos + 'px'
		 		});
		 		window.setTimeout("bigThat.setArrowStateDelayed()", 100);
		 		
		 	},
		 	setArrowStateDelayed: function() {
		 		bigThat.setArrowStatus('right', bigThat.getScrollStatus('right'));
		 		bigThat.setArrowStatus('left', bigThat.getScrollStatus('left'));
		 		
		 	}
			
		}),
	 
	
	PS_miniImageGallery : Class.create({
		initialize: function (gallery) {
			miniThat = this;
			miniThat.previewPics = gallery.select("li");
			miniThat.previewPicsCount = $A(miniThat.previewPics).length; //how much pics do we have
			miniThat.previewPicWidth = miniThat.previewPics[0].getWidth(); //width of a single pic incl margin
			miniThat.scrollWidth = 5 * miniThat.previewPicWidth; //scroll by 2 pictures
			miniThat.listToScroll = $$('#ps_scrollerDiv ul')[0];
			allImageUrls = new Array();
			
			this.setArrowStatus('left', this.getScrollStatus('left'));
			this.setArrowStatus('right', this.getScrollStatus('right'));

			gallery.select("li a")[0].addClassName("ps_active");
			miniThat.previewPics.each(function(clickedPic) {
				Event.observe($(clickedPic).select(".ps_photo")[0], 'mouseover', miniThat.changeProfilePic.bindAsEventListener(this, gallery, clickedPic));
				Event.observe($(clickedPic).select(".ps_photo")[0], 'click', miniThat.openBigSlideshow.bindAsEventListener(null, gallery));
			})
			$$("#ps_scrollerDiv ul")[0].setStyle({ //needed - otherwhise the list will break into next lines
				'width' : miniThat.previewPicsCount * miniThat.previewPicWidth + "px"
			});

			this.leftBtn = gallery.down('#ps_scrollLeft');
			this.rightBtn = gallery.down('#ps_scrollRight');
			Event.observe(this.leftBtn, 'click', this.leftClick.bindAsEventListener(this));
			Event.observe(this.rightBtn, 'click', this.rightClick.bindAsEventListener(this));

			if($('partnerimagelink_openslideshow')) Event.observe($('partnerimagelink_openslideshow'), 'click', this.openBigSlideshow.bindAsEventListener(null, gallery));

			$('ps_imageCountNo').innerHTML = miniThat.previewPicsCount; //set Text n/x
			$('ps_galleryCounterText').removeClassName("ps_inv");
		},
		
		changeProfilePic: function(ev, miniGallery, clickedPic) {
			imageJsonUrl = miniGallery.getAttribute("data-imageJsonUrl");
			imageOwnerId = miniGallery.getAttribute("data-imageOwnerId");
			imagesize = miniGallery.getAttribute("data-imagesize");
			showImageNumber = clickedPic.select("a")[0].getAttribute("data-shownimagenumber");
			imgOrderNo = clickedPic.select("a")[0].getAttribute("data-imgorderno");
			miniThat.previewPics.each(function(picLink) {
				$(picLink).select("a")[0].removeClassName("ps_active");
			})
			$(clickedPic).select("a")[0].addClassName("ps_active");
			
			if(allImageUrls[showImageNumber]) {
				$$(".ps_photo_partnerProfile")[0].style.backgroundImage = "url("+allImageUrls[showImageNumber]+")";
			} else {
				Helper.getImageJsonUrl(imageJsonUrl, imageOwnerId, imagesize, showImageNumber, function(transport) {
					imageLocation = transport.responseText.evalJSON().imageLocation;
					$$(".ps_photo_partnerProfile")[0].style.backgroundImage = "url("+imageLocation+")";
					allImageUrls[showImageNumber] = imageLocation;
				})
			}
			
			if($("partnerimagelink_openslideshow")) {
				$("partnerimagelink_openslideshow").setAttribute("data-shownImageNumber", showImageNumber);
				$("partnerimagelink_openslideshow").setAttribute("data-imgorderno", imgOrderNo);
			}
			$('ps_currentImageNo').innerHTML = imgOrderNo; //set Text n/x
			
			
		},
		
		
		getScrollStatus: function getScrollStatus(arrow) {
			if(arrow == "left") { 
				if(miniThat.listToScroll.positionedOffset().toArray().first() >= 0){
					return "disabled";
				} else {
					return "enabled";
				}
			} else {
				if (miniThat.listToScroll.positionedOffset().toArray().first() <= -((miniThat.previewPicsCount-5) * miniThat.previewPicWidth)) {
					return "disabled";
				} else {
					return "enabled";
				}
			}
		},
		
		setArrowStatus: function setArrowStatus(arrow, status) {
			if(arrow == "left") { 
				if(status == "disabled") {
					$("ps_scrollLeft").addClassName("ps_disabled");
				} else {
					$("ps_scrollLeft").removeClassName("ps_disabled");
				}
			} else {
				if(status == "disabled") {
					$("ps_scrollRight").addClassName("ps_disabled");
				} else {
					$("ps_scrollRight").removeClassName("ps_disabled");
				}
			}
		},
		
		leftClick: function() {
			if(this.getScrollStatus("left") == "enabled") {
				new Effect.Move(miniThat.listToScroll, {
	 				x: miniThat.scrollWidth,
	 				y: 0,
	 				duration: 0.3,
	 				queue: {
	 					scope: 'imageflow',
	 					limit: 1
	 				},
	 				afterFinish : function() {
	 					miniThat.setArrowStatus('left', miniThat.getScrollStatus('left'));	 					
	 					miniThat.setArrowStatus('right', miniThat.getScrollStatus('right'));	 					
	 				}
	 			});	
			}
			
		},
		
		rightClick: function() {
			if(this.getScrollStatus("right") == "enabled") {
				new Effect.Move(miniThat.listToScroll, {
	 				x: -miniThat.scrollWidth,
	 				y: 0,
	 				duration: 0.3,
	 				queue: {
	 					scope: 'imageflow',
	 					limit: 1
	 				},
	 				afterFinish : function() {
	 					miniThat.setArrowStatus('right', miniThat.getScrollStatus('right'));
	 					miniThat.setArrowStatus('left', miniThat.getScrollStatus('left'));
	 				}
	 			});
			}
			
		},
		
		openBigSlideshow: function(ev, miniGallery) {
			if($('partnerimagelink_openslideshow')) {
				var showPicNo = parseInt($('partnerimagelink_openslideshow').getAttribute("data-imgorderno") -1);
				var bigSlideShowUrl = $('partnerimagelink_openslideshow').getAttribute("data-bigSlideshowUrl") + "?userid=" + $('ps_partnerUserId').innerHTML;
				Modalbox.show(bigSlideShowUrl, {width: 460, skin: '1', hideCloseLink: false, confirmBeforeClosing: false, afterLoad:function() {
					bigGalleryInstance = new PageContext.PS_bigImageGallery($('ps_bigSlideshow'));
					bigGalleryInstance.showGalleryImage(showPicNo);
				}});
			}
		}
	}),
		
		
	 PS_listViewRow : Class.create({
		initialize: function (ele, listViewInput) {
			this.ele = $(ele);
			this.rowLinkHref = false;
			this.disabled = false;
			this.useHoverEffect = true;
			
			var t = this;
			// read params
			if (this.ele.className) {
				this.ele.className.split(" ").each(function (v) {
					if (v.match(/^ps_overOnClass_.+$/)) {
						t.overOnClass = v.replace('ps_overOnClass_', '');
					}
					if (v === "ps_disabled") {
						t.disabled = true;
					}
					if (v === "ps_disableHover")
						t.useHoverEffect = false;
				});
			}
			var thisRow = this;

			if (!this.disabled) {
				var globalLinkElem = this.ele.select('.ps_listViewRowGlobalLink').first();
				if (globalLinkElem) thisRow.rowLinkHref = globalLinkElem.getAttribute('href');

				if (listViewInput) {
					this.listInput = this.ele.down('input[name="' + listViewInput + '"]');
					if (this.listInput && this.listInput.checked) {
						this.move();
					}
				}

				if (!this.useHoverEffect) {
					
				} else if (this.overOnClass) {
					// special case: mouesover for row is only triggered by subelements
					// with a certain class
					var overSubElems = this.ele.select('.' + this.overOnClass);
					if (overSubElems) overSubElems.each(function (subElem) {
						Event.observe(subElem, "PS:mousemover", t.move.bindAsEventListener(t));
						Event.observe(subElem, "mousemove", t.move.bindAsEventListener(t));
						Event.observe(subElem, "PS:mouseoutr", t.outside.bindAsEventListener(t));
						Event.observe(subElem, "mouseout", t.outside.bindAsEventListener(t));
						subElem.fire("PS:mousemover");
						subElem.fire("PS:mouseoutr");
					});
				} else {
					Event.observe(this.ele, "PS:mousemover", this.move.bindAsEventListener(this));
					Event.observe(this.ele, "mousemove", this.move.bindAsEventListener(this));
					Event.observe(this.ele, "PS:mouseoutr", this.outside.bindAsEventListener(this));
					Event.observe(this.ele, "mouseout", this.outside.bindAsEventListener(this));
					this.ele.fire("PS:mousemover");
					this.ele.fire("PS:mouseoutr");
				}

				if (this.rowLinkHref) {
					Event.observe(this.ele, "click", this.click.bindAsEventListener(this));
					new Helper.disableHref(this.ele);
					this.ele.style.cursor = 'pointer';
				}

				this.ele.select('.ps_listViewCol').each(function (col) {
					col.className.split(" ").each(function (c) {
						if (c == 'ps_listViewCol_clickable') {
							if (col.getElementsBySelector('a').length > 0) {
								col.style.cursor = 'pointer';
								href = col.getElementsBySelector('a').first().href;
								Event.observe(col, "click", thisRow.columnClick.bindAsEventListener(thisRow, href));
							}
						}
					});
				});


				this.ele.select('.ps_listViewCol_noClick').each(function (col) {
					Event.observe(col, "click", thisRow.stopEventBubbeling.bindAsEventListener(this));
				});


			}
		},

		stopEventBubbeling: function (event) {
			Event.stop(event); // so when clicking on a noClick Row that no other
			// events will be executed
		},

		move: function () {
			this.ele.addClassName("ps_over");
		},

		outside: function (event) {
			if (!this.listInput || !this.listInput.checked) {
				var mouseX = Event.pointerX(event);
				var mouseY = Event.pointerY(event);
				var x = this.ele.cumulativeOffset().left + 2;
				var y = this.ele.cumulativeOffset().top + 2;
				var width = this.ele.getDimensions().width - 4;
				var height = this.ele.getDimensions().height - 4;

				var stillInside = mouseX > x && mouseX < x + width && mouseY > y && mouseY < y + height;
				if (this.overOnClass || !stillInside) this.ele.removeClassName("ps_over");
			}
		},

		click: function (event) {
			// first check, if the mouse has clicked on a div with noClick='true'
			var mouseX = Event.pointerX(event);
			var mouseY = Event.pointerY(event);
			var noLinkElems = this.ele.select(".ps_listViewCol_noClick");

			var canClick = true;
			if (noLinkElems) {
				var i = 0;
				while (canClick && i < noLinkElems.length) {
					var curr = noLinkElems[i];
					var x = curr.cumulativeOffset().left;
					var y = curr.cumulativeOffset().top;
					var width = curr.getDimensions().width;
					var height = curr.getDimensions().height;
					canClick = ((mouseX < x) || (mouseX > (x + width))) || ((mouseY < y) || (mouseY > (y + height)));
					i++;
				}
			}
			// go to global link, if configured and mouse not on a noClick element
			if (this.rowLinkHref && canClick && !this.disabled) window.location.href = this.rowLinkHref;
		},

		columnClick: function (event, href) {
			window.location.href = href;
		}

	}),
		
	/* In Profile */
	PS_makeWritableNote : Class.create({
		initialize: function (elem) {
			this.elem = elem;
			this.elem.observe('click', this.write.bind(this));
			if ($('ps_field_note').value == $('ps_field_note_label').innerHTML) {
				$('ps_field_note').setStyle({
					color: '#999'
				});
			}
		},
		write: function () {
			$$('.ps_openNotebox')[0].addClassName('ps_inv');
			$('ps_field_note').readOnly = false;
			$('ps_field_note').removeClassName('ps_isReadonly');
			if ($('ps_field_note').value == $('ps_field_note_label').innerHTML) {
				$('ps_field_note').value = "";
			}
			$('ps_field_note').focus();
			$('ps_field_note').setStyle({
				color: '#000'
			});
		}
	}),
	
	PS_resetNoteForm : Class.create({
		initialize: function (elem) {
			this.elem = elem;
			this.elem.observe('click', this.cancel.bind(this));
		},

		cancel: function () {
			$$('.ps_openNotebox')[0].removeClassName('ps_inv');
			$('ps_field_note').readOnly = true;
			$('ps_field_note').addClassName('ps_isReadonly');
			$('ps_field_note').value = $('ps_noteTextKeeper').value;
			if ($('ps_field_note').value == $('ps_field_note_label').innerHTML) {
				$('ps_field_note').setStyle({
					color: '#999'
				});
			}
		}
	}),
		
	//on ListPages trigger sorting from SelectBox
	PS_sorting : Class.create({
		initialize: function (elem) {
			elem.observe('change', this.doSorting.bind(this, elem));
		},
		doSorting:function(elem, ev) {
			formUrl = elem.up('form').action;
			if (elem.options[elem.selectedIndex].value != "") {
				submitUrl = formUrl + elem.options[elem.selectedIndex].value;
			}
			else {
				submitUrl = $('baseMemberUrl').value;
			}
			document.location.href = submitUrl;
		}
	}),

	/**
	 * Toggles IntroLinks on Profile and Settings Pages. could not be replaced with :hover easily
	 * */
	PS_introLinks : Class.create({
		initialize: function (elem) {
			that = this;
			elem.each(function(aEle) {
				aEle.observe('mouseover', that.hightlight.bind(that, aEle));	
				aEle.observe('mouseout', that.lowlight.bind(that, aEle));	
			});
			
		},
		
		hightlight: function (elem, ev) {
			bgElem = elem.up('div');
			hoverElem = elem.up('li').className;
			bgElem.addClassName(hoverElem + '_hover'); 
		},
		
		lowlight: function (elem, ev) {
			bgElem = elem.up('div');
			hoverElem = elem.up('li').className;
			bgElem.removeClassName(hoverElem + '_hover'); 
		}

	}),
	
		
	//Save Motto in rightCol
    PS_mottoBox : Class.create({
		initialize: function (ele) {
			that = this;
			//thatResetForm = this.resetForm;
			//thatSubmitForm = this.submitForm;
			textareaEle = $('ps_mottoTextarea');
			this.savedMotto = $F('ps_mottoTextarea');
			new Helper.updateTextareSize(textareaEle);

			new Helper.disableHref($('ps_resetMottoForm'));
			new Helper.disableHref($('ps_mottoSave'));
			
			Event.observe(textareaEle, 'focus', this.showEditMode.bindAsEventListener(this));
			Event.observe($('ps_resetMottoForm'), 'click', this.resetForm.bindAsEventListener(this));
			Event.observe($('ps_mottoSave'), 'click', this.submitForm.bindAsEventListener(this));
		},
		
		showEditMode: function() {
			$$('#ps_mottoBox .ps_buttonRow')[0].removeClassName("ps_inv");
			$$('#ps_mottoBox .ps_inputLimitCounter')[0].removeClassName("ps_notVisible");
		},
		
		hideEditMode: function() {
			$$('#ps_mottoBox .ps_buttonRow')[0].addClassName("ps_inv");
			$('ps_mottoTextarea').removeClassName("ps_inEditMode");
			$$('#ps_mottoBox .ps_inputLimitCounter')[0].addClassName("ps_notVisible");
		},
		
		resetForm: function () {
			$('ps_mottoTextarea').value = theMottoBox.savedMotto;
			theMottoBox.hideEditMode();
		},

		submitForm: function() {
			$$('#ps_mottoBox .ps_indicator')[0].removeClassName("ps_inv");
			var theForm = $('ps_mottoBox');
			url = theForm.action;
			checkStatusValue = this.checkStatusValue;
			if(typeof allInputDefaults !== 'undefined') { allInputDefaults.clearDefaultValuesBeforeSubmit($('ps_mottoBox')); }

			parameters = theForm.serialize(true);
			new Ajax.Request(url + '?rand=' + Helper.getAntiCache(), {
				method: 'post',
				onSuccess: function (transport) {
					$$('#ps_mottoBox .ps_indicator')[0].addClassName("ps_inv");
					checkStatusValue(transport.responseText.evalJSON().userMottoStatus);
					theMottoBox.savedMotto = transport.responseText.evalJSON().userMotto;
					if(typeof allInputDefaults !== 'undefined') { allInputDefaults.fillDefaultValuesAfterSubmit($('ps_mottoBox')); }
				},
				parameters: parameters
			});
		},
		
		checkStatusValue: function (userMottoStatus) {
			$$('.ps_mottoTexts').each(function (ele) {
				ele.setStyle({display: 'none'});
			});
			if (userMottoStatus == "0") {
				$('ps_motto_waitApprove').setStyle({display: 'block'});
			}
			if (userMottoStatus == "-1") { //rejected
				$('ps_motto_rejected').setStyle({display: 'block'});
			}
			theMottoBox.hideEditMode();
			Par.Helper.publishEvent("Par:PageContext:action:updateProfileCompletion", {});
		}
		
	}),
	
	
	//Filters on partnersuggestion-List
	PS_searchFilters : Class.create({
		initialize: function (ele) {
			that = this;
			$$('.ps_searchFilters select').each(function (elem) {
				elem.observe('change', that.selectFilter.bind(this, elem));
			});
			if($('ps_deactivateFilter')) $('ps_deactivateFilter').observe('click', that.resetFilter.bind(this, 2));
			if($('ps_startFiltering')) $('ps_startFiltering').observe('click', that.startFilter.bind(this, 2));

		},

		selectFilter: function (elem) {
			var atLeastOneFilterSelected = false;
			var url = $('filterHitsCountUrl').value;
			var parameters = $('ps_searchFilterForm').serialize();
			$$('.ps_searchFilters select').each(function (elem) {
				if (elem.options.selectedIndex > 0) {
					atLeastOneFilterSelected = true;
				}

			});
			if (atLeastOneFilterSelected == false) {
				that.resetFilter(elem);
			} else {
				new Ajax.Request(url, {
					method: 'post',
					onSuccess: function (transport) {
						myJson = transport.responseText.evalJSON();
						if (Object.isUndefined(myJson.errorOn) || Object.keys(myJson.errorOn).length == 0) { // noError
							that.fillFilteredNumber(myJson.hitsForAll);
							$$('.ps_resetFilter')[0].removeClassName('ps_inv');
							$('ps_startFiltering').removeClassName('ps_buttonDisabled');
						}
						else {
							$$('.ps_resetFilter')[0].addClassName('ps_inv');
							$('ps_startFiltering').addClassName('ps_buttonDisabled');
							$('ps_filterError').removeClassName('ps_inv');
						}

					},
					parameters: parameters
				});
			}

		},

		fillFilteredNumber: function (filteredNumber) {
			$('ps_filteredNumber').innerHTML = filteredNumber;
		},

		startFilter: function (elem) {
			if ($('noFilterRightUrl') != null) {
				url = $('noFilterRightUrl').value;
			}
			else {
				url = $('ps_searchFilterForm').action + "?action=applyAndFilter";
			}

			window.location.href = url;
			return false;
		},
		resetFilter: function (elem) {
			url = $('ps_searchFilterForm').action + "?action=removeFilter";
			window.location.href = url;
			return false;
		}
	}),
	

	//Calcualte passwordStrength (Homepage and dataAndSettings and renewpassword)
	PS_passwordDynamic : Class.create({
		initialize: function (ele) {
			checkPasswordStrength = new PS_checkPasswordStrength();
			
			ele.observe('keyup', function () {
				checkPasswordStrength.keyup(this);
			});
			ele.observe('focus', function () {
				checkPasswordStrength.keyup($F(this));
			});
			
			
			ele.up('form').select('.ps_hideEditBox').each(function (el) {
				el.observe('click', function () {
					$$('.ps_pwdStrengthType').each(function (s) {
						s.hide();
					});
				});
			});
		}
	}),
	
	
	/**
	 * @class
	 * @description When User changes his OnlineStatus in Data&Settings - update the status in my_profile_head 
	 */
	PS_updateOnlineStatus : Class.create(
		/**@lends PageContext.PS_updateOnlineStatus */
		{ 
		initialize: function () {
			if($('ps_field_online0') != null) {
				if($('ps_field_online0').checked) {//allows to show to partnerUser
					$('ps_lastOnlineNow').show();
					$('ps_lastOnlineDate').hide();
				} else {
					$('ps_lastOnlineNow').hide();
					$('ps_lastOnlineDate').show();
				}
			}
		}
	}),
	
	
	/**
	 * @class
	 * @description for all Ajax Forms on Profilepages
	 */
	PS_showEditBox : Class.create({
		initialize: function (ele) {
			this.ele = ele;
			this.boxHandler = new PageContext.PS_showEditBoxHandler();
			if (ele.id) {
				Event.observe(ele, "click", this.click.bindAsEventListener(this));
				Event.observe(ele, "ps:click", this.click.bindAsEventListener(this));
			}
		},
		click: function (evt) {
			this.boxHandler.handle(this.ele, true);
		}
	}),
	

	PS_showEditBoxHandler : Class.create({
		initialize: function () {},
		handle: function (e, scroll) {
			var className = null;
			var cn = e.className.split(' ');
			var i = 0;
			var prefix = 'ps_openEditModeTarget_';
			while (className == null && i < cn.length) {
				if (cn[i].startsWith(prefix)) {
					className = cn[i].substring(prefix.length, cn[i].length);
				}
				i++;
			}

			if (className != null) {
				className = className.strip();
				$(className).up('form').addClassName('ps_highlight');
				
				// hide icon
				if ($(className)) $(className).hide();
				var elems = $$('.' + className);
				if (elems) {
					elems.each(function (ele) {
						if (ele.id.endsWith('_active')) {
							ele.show();
						} else {
							ele.hide();
						}
					});
				}
			}
		}
	}),
	
	/**
	 * @class
	 * @description On Profile-Pages hide Boxes after editing
	 */
	PS_hideEditBox : Class.create({
		initialize: function (ele) {
			this.ele = $(ele);
			this.idPrefix = null;
			var cn = this.ele.className.split(' ');
			var i = 0;
			var prefix = 'ps_hideEditBoxTarget_';
			while (this.idPrefix == null && i < cn.length) {
				if (cn[i].startsWith(prefix)) {
					this.idPrefix = cn[i].substring(prefix.length, cn[i].length);
				}
				i++;
			}
			if (this.idPrefix != null) {
				if (this.ele.hasClassName('ps_resetFormWhenNoErrors')) {
					Event.observe(this.ele, "click", this.resetFormWhenNoErrors.bindAsEventListener(this));
				}
				
				var justHide = this.ele.hasClassName('ps_noUnconditionalFormReset');
				Event.observe(this.ele, "click", this.click.bindAsEventListener(this, justHide));

				Event.observe(this.ele, "ps:click", this.click.bindAsEventListener(this));
				Event.observe(this.ele, "ps:hide", this.click.bindAsEventListener(this, true)); // Just close everything, BUT do not reset Form (Mantis#63424)
			}
		},
		
		resetFormWhenNoErrors: function(evt) {
			var form = $(this.ele).up('form'); 
			if (form.select('.ps_hasError').length == 0)
				form.reset();
		},
		
		click: function (evt, justHide) {
			evt.stop();
			var className = this.idPrefix;
			$(className).up('form').removeClassName('ps_highlight');
			var elems = $$('.' + className);
			if (elems) {
				elems.each(function (ele) {
					if (ele.id.endsWith('_active')) {
						ele.hide();
						if(ele.up('.ps_hasError') != null) {
							ele.up('.ps_hasError').select('.ps_profileEditInputBox .ps_errorBox')[0].hide();
							ele.up('.ps_hasError').removeClassName("ps_hasError");
						}
						// new Effect.BlindUp(ele);
					}
					else {
						ele.show();
						// new Effect.BlindDown(ele);
					}
				});
			}
			// show icon
			$(className).show();
			if (!justHide) {
				if ($(className).up('form')) $(className).up('form').reset();
			}
		}
	}),
	

	/**
	 * @class
	 * @description Handle Forms in Profile-Section
	 */
	PS_profileForms : Class.create({
		initialize: function (submittedForm, theTransport) {
			transport = theTransport;
			myHideError = this.hideError;
			mySubmittedForm = submittedForm; // an ID of that specific form that
			// should be submitted
			myCollectFormValues = this.collectFormValues;
			myToggleFormDisplay = this.toggleFormDisplay;
			myShowError = this.showError;
			myDisplayValueReady = this.displayValueReady;
			myHasError = false;
		},

		/**
		 * @description Aufruf, nachdem die angeforderte Seite erfolgreich geladen wurde.
		 */
		ajaxCompletedSuccess: function () {
			model = transport.responseText.evalJSON();
			if (Object.isUndefined(model.errorMessages) || Object.keys(model.errorMessages).length == 0) { // noError
				
				myHasError = false;
				// When no error occured check if we have a profileCompletion Box on page. If so do a Ajax-refresh on that Box
				if (($$('.ps_profile_edit_page')[0] || $$('.ps_dataandsettingsPages')[0]) && $$('.ps_statusBar')[0]) {
					Par.Helper.publishEvent("Par:PageContext:action:updateProfileCompletion", {});
					new PageContext.PS_updateOnlineStatus();
				}
				
				//show or hide the approval box, if approved status map is not empty
				if(!Object.isUndefined(model.approvedStatusMap) && Object.keys(model.approvedStatusMap).length == 1) {
					approvedStatus = Object.values(model.approvedStatusMap);
					if (approvedStatus == 'APPROVED') {
						myWithApprovalBox = false;
						notActiveDiv = $(mySubmittedForm).select('div.ps_notActivatedBox')[0];
						if (notActiveDiv != null) {
							notActiveDiv.hide();
						}
						rejectedDiv = $(mySubmittedForm).select('div.ps_rejectedBox')[0];
						if (rejectedDiv != null) {
							rejectedDiv.hide();
						}
					} 
				     
				}

				// show Modalbox when changes affect Matchingpoints
				if (!Object.isUndefined(model.matchingPointsWillChange) && model.matchingPointsWillChange == true) {
					Modalbox.show($('ps_modal_matchingPointsWillChange'), {
						width: 540,
						skin: '1',
						hideCloseLink: false
					});
				}

				// Hide ErrorMessage if there is one
				myHideError();
				// take all form-elements and put selected/filled values to
				// concatedString-Array
				concatedString = myCollectFormValues();
				// open / close Form
				myToggleFormDisplay();
				// write saved vales to DOM
				saveFormToDOM($(mySubmittedForm));
				// Close open Form
				$(mySubmittedForm).select('.ps_hideEditBox')[0].fire('ps:hide');
			}
			else {
				myHasError = true;
				myShowError(model.errorMessages);
			}
			// this.hideIndicator(replaceContainer);
		},

		collectFormValues: function () {
			// Collect all checked CHECKBOX and put Text into Array
			var newValueArray = new Array();
			if ($(mySubmittedForm).select('input[type=checkbox]')[0]) {
				$(mySubmittedForm).select('input[type=checkbox]').each(function (elem) {
					if ($(elem.id).checked) {
						newValueArray.push($(elem.id + "_label").innerHTML.strip());
					}
				});
				value = newValueArray.join(", ");
			}
			// Collect all checked RADIO and put Text into Array
			if ($(mySubmittedForm).select('input[type=radio]')[0]) {
				$(mySubmittedForm).select('input[type=radio]').each(function (elem) {
					if ($(elem.id).checked) {
						newValueArray.push($(elem.id + "_label").innerHTML.strip());
					}
				});
				value = newValueArray.join(", ");
			}
			// Collect all INPUT-TEXT and put Text into Array
			if ($(mySubmittedForm).select('input[type=text]')[0]) {
				$(mySubmittedForm).select('input[type=text]').each(function (elem) {
					if ($(elem).value.strip() != "") {
						newValueArray.push($(elem).value.strip());
					}
				});
				value = newValueArray.join(", ");
			}
			// Collect all TEXTAREA and put Text into Array
			if ($(mySubmittedForm).select('textarea')[0]) {
				$(mySubmittedForm).select('textarea').each(function (elem) {
					if ($(elem).value.strip() != "") {
						newValueArray.push(elem.value.strip());
					}
				});
				value = newValueArray.join(", ");
			}

			concatedString = "";
			$A(value).each(function (displayText) {
				concatedString = concatedString + displayText;
			});

			if (concatedString.search(/\./) > 0) { // factfile/overview has whole
				// sentences. If sentence we
				// have no "," between them
				concatedString = concatedString.gsub(',', '');
			}
			return concatedString;
		},

		toggleFormDisplay: function () {
			notActiveDiv = null;
			displayTextDiv = $(mySubmittedForm).select('.ps_form_element_display')[0];
			emptyDiv = $(mySubmittedForm).select('.ps_emptyInput')[0];
			// PS.debug(concatedString +" ##### "+ displayTextDiv.innerHTML);
			if (concatedString != displayTextDiv.innerHTML) {
				if (myWithApprovalBox != null && myWithApprovalBox) {
					notActiveDiv = $(mySubmittedForm).select('div.ps_notActivatedBox')[0];
				}
				if (concatedString == "") { // no value selected or Text entered
					if (notActiveDiv != null) {
						notActiveDiv.hide();
					}
					if (emptyDiv != null) {
						emptyDiv.show();
					}
					displayTextDiv.hide();
				}
				else {
					if (notActiveDiv != null) {
						notActiveDiv.show();
					}
					if (emptyDiv != null) {
						emptyDiv.hide();
					}
					displayTextDiv.show();
				}

			}
			else {
				// PS.debug("nothing changed");
			}
			concatedString = concatedString.replace("<", "");
			concatedString = concatedString.replace(">", "");
			displayTextDiv.innerHTML = concatedString;
			myDisplayValueReady = true;
		},

		showError: function (errorMessages) {
			// get all errorMessages (probably more than one)
			errorText = "";
			poststring = "";
			if (!Object.isArray(errorMessages)) {
				for (var sub in errorMessages) {
					PS.debug(errorMessages[sub]);
					if (errorText != "") poststring = "<br />";
					errorText = errorText + errorMessages[sub] + poststring;
				}
			}
			$(mySubmittedForm).addClassName("ps_hasError");
			$(mySubmittedForm).select('.ps_profileEditInputBox .ps_errorBox .ps_errorText')[0].innerHTML = errorText;
			$(mySubmittedForm).select('.ps_profileEditInputBox .ps_errorBox')[0].show();
		},

		hideError: function () {
			$(mySubmittedForm).removeClassName("ps_hasError");
			$(mySubmittedForm).select('.ps_profileEditInputBox .ps_errorBox')[0].hide();
		},

		isErrorOccured: function () { // give back if an error occured
			if (myHasError) {
				return true;
			}
			else {
				return false;
			}
		},

		isDisplayValueReady: function () { // give back if displayValue String is
			// ready and displayed
			PS.debug('myDisplayValueReady: ' + myDisplayValueReady);
			if (myDisplayValueReady) {
				return true;
			}
			else {
				return false;
			}
		},

		getSubmittedForm: function () {
			return mySubmittedForm;
		}

	}),
	

	/**
	 * @class
	 * @description Boxes on /payment/runtime 
	 * */
	PS_productBox : Class.create({
		initialize: function (ele) {
			this.ele = $(ele);
			this.boxClasses = ['ps_productBox', 'ps_selectedProduct', 'ps_productBoxHorizontal', 'ps_productBoxHorizontalWithSeal'];
			this.boxClasses.each(function (c) {
				if (this.ele.hasClassName(c)) this.boxType = c;
			}, this);
			Event.observe(this.ele, "click", this.click.bindAsEventListener(this));
			Event.observe(this.ele, "mouseover", this.inside.bindAsEventListener(this));
			Event.observe(this.ele, "mouseout", this.outside.bindAsEventListener(this));
			if (this.ele.down('input')) {
				new Field.Observer(this.ele.down('input'), 0.05, this.checkradios.bind(this));
			}
			this.checkForMonthly();
		},
		click: function () {
			var id = this.ele.id;
			if ($(id + '_input')) {
				$(id + '_input').click();
			}

		},
		inside: function (evt) {
			try {
				e = evt.element().up("." + this.boxType) || evt.element();
				e.addClassName(e.id + "_on");
				e.addClassName(this.boxType + "_on");
			}
			catch (e) {}
		},
		outside: function (evt) {
			try {
				e = evt.element().up("." + this.boxType) || evt.element();
				if (!$F(e.down('input'))) {
					e.removeClassName(e.id + "_on");
					e.removeClassName(this.boxType + "_on");
				}
			}
			catch (e) {}
		},
		checkradios: function (el, v) {
			e = el.up("." + this.boxType);
			if (!$F(e.down('input'))) {
				e.removeClassName(e.id + "_on");
				e.removeClassName(this.boxType + "_on");
			}
			this.checkForMonthly();
		},

		checkForMonthly: function () {
			if ($('ps_productBox4') != null && $('ps_monthly_Payment') != null) {
				theCheckbox = $$('#ps_productBox4 input[type=radio]')[0];
				if (theCheckbox.checked) {
					$('ps_monthly_Payment').addClassName("ps_inv");
					$('ps_field_mon_payment').disabled = true;
					$('ps_toggleArea_ps_monthly_Payment').hide();
				} else {
					$('ps_monthly_Payment').removeClassName("ps_inv");
					$('ps_field_mon_payment').disabled = false;
				}
			}
		}
	}),
	
	/**
	 * @class
	 * @description Tab Navigation on payment/method Page
	 * */
	PS_paymentNavTab: Class.create(
		/** @lends PageContext.PS_paymentNavTab */	
		{
		initialize: function(ele){
			that = this;
			var clickElems = ele.select('a');			
			var last = $A(clickElems).size();			
	        $A(clickElems).each(function(el, index) {
	        	el.observe('click', that.click.bind(that, el));	        	
	        	if(index == last-1) {el.up('li').addClassName("ps_last");}	        	
	        })
	        
			
	    },
	    click: function(el, ev) {
	    	ev.stop();
	    	var clickedEle = el.up();
	    	var showPaymentMethod = clickedEle.id.substring(7, clickedEle.id.length);
	    	var prefix = "ps_payment_method_";
	    	$$('.ps_tabList li').each(function(methodNav) { //reset tabNav
	    		methodNav.removeClassName("ps_active");
	    	})
	    	$$('.ps_methodBox').each(function(methodEl) { //reset methodBoxes
	    		methodEl.hide();
	    	})
	    	$(clickedEle).addClassName("ps_active");
	    	$(prefix + showPaymentMethod).show();
	    }
	}),


	
	

	/**
	 * @class
	 * @description For fake Systemmail via Parmaconto on Welcomepage / inbox. we have to count one Message up
	 * */
	PS_welcomeMail : Class.create({
		initialize: function (ele) {
			if ($('ps_messagesHeadline') != null) {
				msgCount = $$('#ps_messagesHeadline')[0].innerHTML;
				PS.debug("msgCount=" + msgCount);

				oldMsgCount = msgCount.match(/\d+/);
				PS.debug("oldMsgCount=" + oldMsgCount);
				newMsgCount = parseInt(oldMsgCount) + 1;
				$('ps_messagesHeadline').innerHTML = $('ps_messagesHeadline').innerHTML.replace(/\d+/, newMsgCount);
			}
			if ($$('.ps_noEntriesText')[0] != null) {
				$$('.ps_noEntriesText')[0].addClassName('ps_inv');
			}

		}
	}),
	
	/**
	 * @class
	 * @description On welcomepage - in newAtParship-Box 
	 * */
	sendAGreeting : Class.create({
		initialize: function (partner, url, ev) {
			that = this;
			checkReciprocal = new PageContext.PS_ac_reciprocal();
			if($$('.quidProQuoType')[0] != null) {
				checkReciprocal.click($$('.quidProQuoType')[0].value + partner, null);
				if(checkReciprocal.isBlocked()) return false;
			}
			

			new Ajax.Request(url, {
				parameters: {
					partnerId: partner
				},
				onSuccess: function showMe(response) {
					var myJson = response.responseText.evalJSON();
					if (myJson.messageId) {
						Modalbox.show($('ps_modal_greetings'), {
							width: 340,
							skin: '6',
							hideCloseLink: false
						});
						if ($('ps_greeting_' + partner) != null) {
							$('ps_greeting_' + partner).hide();
							// Show link to send greetings message
							if ($('ps_greeted_' + partner) != null) {
								elem = $('ps_greeted_' + partner);
								elem.show();
								// elem.observe("click", gotoGreeted()"+ elem.href +
								// myJson.messageId + "'");
								Event.observe(elem, "click", that.gotoGreeted.bindAsEventListener(ev, elem.href + myJson.messageId));
								Event.stop(ev);
							}
						}
					}

				}
			});
		},
		
		gotoGreeted: function(ev, url) {
			document.location.href = url;
		}
	}),
	
	

	/**
	 * @class
	 * @description For reporting bad Profiles 
	 * */
	PS_reportProfile : Class.create({
		initialize: function (whichTab) {
			that = this;
			Event.observe(whichTab, 'click', function() {
				Modalbox.show($$('.ps_reportProfile')[0].readAttribute('data-modalurl'), {width: 570,  skin: '1', afterLoad:function() { //hier die url rein
					Event.observe($('ps_submitReportProfile'), 'click', that.submitForm);	
				}});
				
			});	
		},
		
		submitForm: function() {
			var theForm = $('partner_report_profile_form');
			var url = theForm.action;
			
			if($('ps_reportReasonFreetext').value == $('ps_reportReasonFreetext_label').innerHTML) {
			    $('ps_reportReasonFreetext').value = "";
			}
			
			new Ajax.Request(url, {
				parameters: theForm.serialize(),
				onSuccess: function(response) {
					var myJson = response.responseText.evalJSON();

					var cleared = false;
					//if user didn't enter a message
					if($('ps_reportReasonFreetext').value == $('ps_reportReasonFreetext_label').innerHTML) {
						$('ps_reportReasonFreetext').value = "";
						cleared = true;
					}
					var dheight = $("reportProfileForm").getHeight();
					var nheight;
					if(myJson.successful){
						$( "reportProfileForm" ).hide();
						$( "reportProfileSuccess" ).show();
						nheight = $("reportProfileSuccess").getHeight();
						Modalbox.autoresizeHeight();	
					} else {
						$("ps_reportError").removeClassName("ps_inv");
						$("ps_reportError").show();
						Modalbox.autoresizeHeight();
					}
					
					if(cleared) {
						$('ps_reportReasonFreetext').value = $('ps_reportReasonFreetext_label').innerHTML;
					}
					
				}
			});
		}
	}),

	/**
	 * @class
	 * @description User for intern/ and openCMS-Poll 
	 * */
	PS_potw : Class.create({
		initialize: function () {
		},
		
		displayIntern: function() {
			var country = $F('countryFree') ? $F('countryFree') : $F('country');
			this.queryData($F('pollid'), country, $F('sex'), function (potw) {

				function createTd(tr, text) {
					var td = new Element('td');
					td.update(text);
					tr.insert(td);
				};

				var reportContainer = $('potwReport');
				// Remove all elements
				reportContainer.update('');

				var headerElem = new Element('h2').update('Result for pollId: ' + $F('pollid') + ', country: ' + country + ', sex: ' +$F('sex'));
				reportContainer.insert(headerElem);

				var tableElem = new Element('table', {id: 'ps_potwTable'});
				tableElem.innerHTML = '<thead><tr><th>Question</th><th>Male %</th><th>Male &sum;</th><th>Female %</th><th>Female &sum;</th></tr></thead>';
				
				var tbody = new Element('tbody');
				for (var question in potw.answers) {
					var answer = potw.answers[question];
					var tr = new Element('tr');
					createTd(tr, question);
					createTd(tr, answer.malePercentage + '%');
					createTd(tr, answer.maleSum);
					createTd(tr, answer.femalePercentage + '%');
					createTd(tr, answer.femaleSum);
					tbody.insert(tr);
				}
				tableElem.insert(tbody);

				var tfoot = new Element('tfoot');
				tableElem.insert(tfoot);

				var tr = new Element('tr');
				createTd(tr, 'Sum');
				createTd(tr, potw.malePercentage + '%');
				createTd(tr, potw.maleTotal);
				createTd(tr, potw.femalePercentage + '%');
				createTd(tr, potw.femaleTotal);
				tfoot.insert(tr);

				reportContainer.insert(tableElem);
			});
		},
		
		displayCms: function() {
			widthFactor=1.4;
			this.queryData($F('pollid'), $F('country'), $F('sex'), function (potw) {
				myIndex = 0;
				
				allElems = $$('.ps_potw_answer');
				allElems.each(function(ele) {
					ele.select('.ps_pollLine')[0].select('.ps_percentVal')[0].setStyle({width: '0px'}); 
					 ele.select('.ps_pollLine')[1].select('.ps_percentVal')[0].setStyle({width: '0px'}); 
					 ele.select('.ps_label')[0].innerHTML = 0 + "%";
					 ele.select('.ps_label')[1].innerHTML = 0 + "%";
				});
				
				
				for (var question in potw.answers) {
					var answer = potw.answers[question];

					if($$('.ps_potw_answer')[myIndex] != null) {
						ele = $$('.ps_potw_answer')[question-1];

						var malePercentage = answer.malePercentage ? answer.malePercentage : 0;
						malePercentBar = ele.select('.ps_pollLine')[0].select('.ps_percentVal')[0];
						malePercentValue = ele.select('.ps_label')[0];
						
						var femalePercentage = answer.femalePercentage ? answer.femalePercentage : 0;
						femalePercentBar = ele.select('.ps_pollLine')[1].select('.ps_percentVal')[0];
						femalePercentValue = ele.select('.ps_label')[1];
						
						if(malePercentage != 0) {
							newWidth = widthFactor * malePercentage;
							malePercentBar.addClassName("ps_male");
							malePercentBar.setStyle({width: newWidth+'px'}); 
							malePercentValue.innerHTML = Math.round(malePercentage) + "%";
						}
						if(femalePercentage != 0) {
							newWidth = Math.round(widthFactor * femalePercentage);
							femalePercentBar.addClassName("ps_female");
							femalePercentBar.setStyle({width: newWidth+'px'});
							femalePercentValue.innerHTML = Math.round(femalePercentage) + "%";
						}
						myIndex = myIndex + 1;
					}
				}
			});
		},
		
		queryData: function(pollid, country, sex, renderFunction) {
			new Ajax.Request("/potw/json", {method: 'get', parameters: {pollid: pollid, country: country, sex: sex}, onSuccess: function(response) {
				var potwResponse = response.responseText.evalJSON();
				renderFunction(eval(potwResponse.potw.evalJSON()));
			}}); 
		}

	}),
	
	/**
	 * @description For switching Tabs on Testresult pages
	 * */
	changeTestResultArea : function(elm,num) {
		$$('.ps_bgTabbedTestResultBtnOuter_active').each(function(s){
			s.removeClassName('ps_bgTabbedTestResultBtnOuter_active').addClassName('ps_bgTabbedTestResultBtnOuter');
		});
		
		elm.removeClassName('ps_bgTabbedTestResultBtnOuter').addClassName('ps_bgTabbedTestResultBtnOuter_active');
		
		$$('.ps_testResultArea').each(function(s){ 
			s.setStyle({display: 'none'});
		});	
		
		$('ps_testResultArea'+num).setStyle({display: 'block'});
	},
	

	
	/**
	 * @class
	 * @description Message form AJAX submission and error handling
	 *  */
	PS_messageForm : Class.create(
		/**@lends PageContext.PS_messageForm */	
		{
			/**
			 * 
			 * @param {DOMElement} the form element to attach to
			 */
			initialize: function initialize(form) {
				this.form = form;
				this.isDraft = false;
				this.isAutosaved = false;
				this.findFieldsThatDisplayMessages();
				this.transmissionInProgress = false;
				that = this;
				this.form.select('.act_sendMessageButton').each(function(button){
					button.observe('click', that.submitMessage.bind(that));
				});
				
				this.form.select('.act_saveDraftButton').each(function(button){
					button.observe('click', that.submitAsDraft.bind(that));
					button.observe('ps:click', that.submitAsDraft.bind(that));
				});
				this.form.observe('submit', function(e) {
					e.stop();
				});
				this.startAutoSaveDraft();
				
				PS.debug('messageForm ready');
			},
			
			/**
			 * @private
			 * @description finds all form fields that CAN display messages
			 * 				(defined with the [@errorMessagesFor 'fieldname' /] and [@infoMessagesFor 'fieldname' /] macros)
			 */
			findFieldsThatDisplayMessages: function findFieldsThatDisplayMessages() {
				this.fieldsToShowMessagesFor = [];
				this.fieldsToShowMessagesFor['info'] = [];
				this.fieldsToShowMessagesFor['error'] = [];
				
				var regexp	= RegExp("ps_(.*)_(.*)");
				var that	= this;
				
				this.form.select('.ps_formAttributeMessage').each(function(messageBox){
					try {
						var result		= regexp.exec(messageBox.id);
						var fieldName	= result[1];
						var messageType	= result[2];
						
						if (typeof that.fieldsToShowMessagesFor[messageType] === 'undefined') {
							that.fieldsToShowMessagesFor[messageType] = [];
						}
						that.fieldsToShowMessagesFor[messageType].push( fieldName );
					} catch(e) {
						PS.debug(e);
					}
				});
			},
			
			/**
			 * @private
			 * @description click handler for message submit button
			 */
			submitMessage: function submitMessage(event) {
				event.stop();
				this.setDraftStatus(false);
				this.stopAutoSaveDraft();
				this.submit();
			},
			
			
			/**
			 * @private
			 * @description changed Text that has not been saved yet
			 */
			hasUnsavedText: function hasUnsavedText(event, isAutosaved) {
				return true;
			},
			
			/**
			 * @private
			 * @description gives true/false for showing ClosingConfirmationLayer
			 */
			isConfirmBeforeClose: function isConfirmBeforeClose() {
				if((($('subject') && $('subject').type != 'hidden' && !$('subject').hasClassName('ps_defaultValueClass'))) || 
					($('ps_writeMessage') && !$('ps_writeMessage').hasClassName('ps_defaultValueClass')))  { //&& this.hasUnsavedText() == true
					return true;
				} else {
					return false;
				}
			},
			
			/**
			 * @private
			 * @description internally marks the message as a draft (+autoSaved) or a regular message
			 * @param {Boolean} isDraft
			 * @param {Boolean} isAutosaved If triggered via automatic saving
			 */
			setDraftStatus: function setDraftStatus(isDraft, isAutosaved) {
				if ($('ps_saveDraft')) {
					$('ps_saveDraft').value = isDraft;
					this.isDraft = isDraft;
				}
				if (isAutosaved != null && isAutosaved == true) {
					if($('ps_isAutosaved') != null) $('ps_isAutosaved').value = isAutosaved;
					this.isAutosaved = isAutosaved;
				} else {
					if ($('ps_isAutosaved') != null) $('ps_isAutosaved').value = false;
					this.isAutosaved = false;
				}
			},
			/**
			 * @description starts the autosaver process
			 */
			startAutoSaveDraft: function autoSaveDraft() {
				//if messageForm with freetext

				if($('ps_writeNewMessage') && $$('.ps_typeText')[0] != null && $$('.act_saveDraftButton')[0] != null) {//Bug-4854
					if(pageVars.autoSaveDraftInterval != null && pageVars.autoSaveDraftInterval != "0") { //variable not set or set to 0 via SO = no autosave 
						autoSaveDraftInterval = pageVars.autoSaveDraftInterval * 1000;
						var inst = this; 
						autoSaverDraft = setInterval(function(){ 
							inst.submitAsDraft(null, true)
						},autoSaveDraftInterval);
						
						
						
					}
				}
			},
			
			/**
			 * @private
			 * @description click handler for draft submit button
			 */
			submitAsDraft: function submitAsDraft(event, isAutosaved) {
				if ($('ps_writeMessage') != null) {
					if(event != null) event.stop();
					if(typeof allInputDefaults !== 'undefined') { allInputDefaults.clearDefaultValuesBeforeSubmit($$('.ps_messageForm')[0]); }
					if(isAutosaved && ($('subject').value == "" || $('ps_writeMessage').value == "")) {
						if(typeof allInputDefaults !== 'undefined') { allInputDefaults.fillDefaultValuesAfterSubmit($$('.ps_messageForm')[0]); }
						return false;
					}
					this.setDraftStatus(true, isAutosaved);
					this.submit();
				} else {
					this.stopAutoSaveDraft();
				}
			},
			
			/**
			 * @description stops the automatic saving of drafts
			 * */
			stopAutoSaveDraft: function stopAutoSaveDraft() {
				if (typeof autoSaverDraft == "number") {
					window.clearInterval(autoSaverDraft);
				}
			},
			
			activateSubmitButtons: function activateSubmitButtons() {
				this.form.select('.messageFormSubmitButton').each(function(button){
					button.removeClassName('disabledButton');
				});
				this.startAutoSaveDraft(); //when user is able to click on save again we can start again with autosave
			},
			
			disableSubmitButtons: function disableSubmitButtons() {
				this.form.select('.messageFormSubmitButton').each(function(button){
					button.addClassName('disabledButton');
				});
				this.stopAutoSaveDraft();
			},
			
			
			/**
			 * @private
			 * @returns {Boolean}
			 */
			submit: function submit() {
				if (this.transmissionInProgress === true) {
					return false;
				}
				
				if(typeof allInputDefaults !== 'undefined') {
					allInputDefaults.clearDefaultValuesBeforeSubmit(this.form);
				}
				Par.Helper.publishEvent('ps:messageForm:beforeSubmit', { source: this.form, isDraft: this.isDraft, isAutosaved: this.isAutosaved }, this.form);
				
				this.transmissionInProgress = true;
				this.disableSubmitButtons();
				
				this.fieldsToShowMessagesFor['error'].each(function(fieldName){
					var messageBox = $('ps_' + fieldName + '_error');
					messageBox.update();
					messageBox.addClassName("ps_inv");
				});
				
				// TODO: refactor
				this.fieldsToShowMessagesFor['info'].each(function(fieldName){
					var messageBox = $('ps_' + fieldName + '_info');
					messageBox.update();
					messageBox.addClassName("ps_inv");
				});
				
				if(typeof allInputDefaults !== 'undefined') { allInputDefaults.clearDefaultValuesBeforeSubmit($$('.ps_messageForm')[0]); }
				
				new Ajax.Request(this.form.action, {
					method: this.form.method,
					parameters: this.form.serialize(),
					onComplete: this.handleResponse.bind(this),
					onFailure: function() {
						this.transmissionInProgress = false;
						PS.debug("AJAX form submission failed");
					}
				});

				return false;
			},
			
			/**
			 * @private
			 * @param transport
			 * @returns {Boolean|null}
			 */
			handleResponse: function handleResponse(transport) {
				
				this.transmissionInProgress = false;
				transport = transport.responseText.evalJSON();
				var that = this;
				
				if(typeof allInputDefaults !== 'undefined') { allInputDefaults.fillDefaultValuesAfterSubmit($$('.ps_messageForm')[0]); }

				// Assume a fatal error if the error redirect URL is set by the controller, stop here immediately
				if (transport.errorRedirectUrl) {
					Par.Helper.publishEvent('ps:messageForm:submitFailed', { source: this.form, isDraft: this.isDraft, isAutosaved: this.isAutosaved, alert: transport.statusMessage, redirectUrl: transport.errorRedirectUrl }, this.form);
					return false;
				}
				if (transport.infoMessages) {
					this.displayMessagesFromHash('info', transport.infoMessages);
				}
				if (transport.errorMessages) {
					this.displayMessagesFromHash('error', transport.errorMessages);					
					this.activateSubmitButtons();
					Par.Helper.publishEvent('ps:messageForm:submitFailed', { source: this.form, isDraft: this.isDraft, isAutosaved: this.isAutosaved, alert: transport.statusMessage, errorMessages: transport.errorMessages }, this.form);
				} else {
					Par.Helper.publishEvent('ps:messageForm:submitSucceeded', { source: this.form, messageId: transport.messagingPO.messageIdText, isDraft: this.isDraft, isAutoSaved: this.autoSaved, alert: transport.statusMessage, redirectUrl: transport.successRedirectUrl }, this.form);
					if (this.isDraft) {
						this.activateSubmitButtons();
					}
				}
			},
			
			/**
			 * @private
			 * @param messageType
			 * @param hashOfMessageHashes
			 */
			displayMessagesFromHash: function displayMessagesFromHash(messageType, hashOfMessageHashes) {
				messageType = messageType.toLowerCase();
				//has to be a real hash with {} and stuff. Do not just put a String here!
				//PS.debug(typeOf hashOfMessageHashes);
				$H(hashOfMessageHashes).each(function(messageHash){
					var fieldName 		= messageHash.key;
					var messageText		= messageHash.value;
					var messageBox		= $('ps_' + fieldName + '_' + messageType);
					
					// put messages into a 'catch-all' container if no specific container exists for them
					if (!messageBox) {
						var messageBoxId = 'ps_fieldless' + '_' + messageType;
						if (!$(messageBoxId)) {
							$(that.form).insert('<div id="' + messageBoxId + '" class="ps_inv ps_formAttributeMessage ps_formAttributeMessage_' + messageType + '"></div>');
						}
						messageBox = $('ps_fieldless_error');
					}
					
					messageBox.removeClassName("ps_inv");	
					messageBox.insert(messageText);
				});
			}
	}),
	
	/**
	 * @class
	 * @description Glue class for message forms and message forms within modals
	 * 				Displays alerts and handles redirection
	 * 
	 * 				Event payload: expects the <form> element as memo.source
	 *  */
	PS_messageFormHelper : Class.create(
		/**@lends PageContext.PS_messageFormModalHelper */	
		{
			initialize: function initialize() {
				Par.Helper.subscribeEvent('ps:messageForm:submitSucceeded',	this.handleSubmitSuccess.bind(this));
				Par.Helper.subscribeEvent('ps:messageForm:submitFailed', 		this.handleSubmitError.bind(this));
			},
			
			handleSubmitError: function handleSubmitError(event) {
				var message = event.memo;
				
				// If the controller returns a failure redirect URL, we assume the error is fatal
				// and cannot be recovered from. We also stop event propagation, since there is no 
				// use in other subscribers being notified at this point.
				if (message.redirectUrl) {
					event.stop();
					window.location = message.redirectUrl;
					return false;
				}
				
				if (Modalbox.initialized === true) {
					Modalbox.autoresizeHeight();
				}
			},

			handleSubmitSuccess: function handleSubmitSuccess(event) {
				var message = event.memo;
				
				if (message.alert) {
					this.showAlert(message);
					return;
				} 

				//Is this still needed???
				if (message.redirectUrl) {
					window.location = message.redirectUrl;
					return;
				}
				
				if (message.isDraft) {
					if ($('ps_messageIdText')) {
						$('ps_messageIdText').value = message.messageId;
					}
				}
				
				
				if (Modalbox.initialized === true) {
					Modalbox.autoresizeHeight();
				}
				
			},
			
			showAlert: function showAlert(message) {
				$('ps_modalAlertType').addClassName(message.alert.type);
				$('ps_modalAlertText').update(message.alert.text);
				
				Modalbox.show($('ps_statusmessage'), { width: 280, hideCloseLink: false, confirmBeforeClosing: false});
				Modalbox.setSkin(6);
				
				if (message.redirectUrl) {
					Modalbox.options.afterHide = function() { 
						 new PageContext.PS_messagingPageUpdate(message.redirectUrl);
						}.bind(message);
					
				}
			}
	}),

	/**
	 * @class
	 * @description Will handle Updateing of PartnerProfile after a new Message / Smile / Imagerelease has been send
	 */
	PS_messagingPageUpdate : Class.create(
		/**@lends PageContext.PS_messagingPageUpdate */	
		{
			initialize: function initialize(redirectTo) {
				
				if($('ps_contactButtons')) { //only on partner_profile
					new Ajax.Updater('ps_contactButtonsAjaxWrapper', $('ps_contactButtons').readAttribute('data-url'), {
						method: 'get',
						onComplete: function() {
							Par.Helper.publishEvent('Par:Inits:domInit:imageReleaseModal', { }); //triggers events on ajax loaded buttons
							$$('#ps_contactButtons .ps_tooltip').each(function(tip) {
								new Helper.PS_tooltip(tip);
							})
						}
					});
				
					if($('ps_1on1mailboxTab')) {
						if($('ps_1on1mailboxTabContent').hasClassName('ps_inv')) { //is in foreground - reload list
							$('ps_1on1mailboxTab').removeClassName("ps_tabDisabled");
							$('ps_1on1mailboxTab').observe('click', function() {
								Par.PageContext.profileTabs.loadTab('1on1mailbox', 'partnerProfile');
							});
						} else {
							Par.PageContext.profileTabs.loadTab('1on1mailbox', "partnerProfile", false, true);	
						}
					}
					
				} else { //schreibe message im messaging bereich
					location.href = redirectTo;
				}
				
			}
	}),
	
	/**
	 * @class
	 * @description Glue class for executing omniture tracking callbacks when messages are submitted
	 * 
	 * @param callback {Function} callback containing the Omniture click tracking code 
	 */
	PS_messagingOmnitureHelper : Class.create(
		/**@lends PageContext.PS_messagingOmnitureHelper */	
		{
			initialize: function initialize(callback, omnevent) {
				this.callback = callback;
				Par.Helper.subscribeEvent('ps:messageForm:beforeSubmit',	this.notifyOmniture.bind(this, omnevent));
			},
			
			notifyOmniture: function notifyOmniture(omnevent, event) {
				var message = event.memo;
				if (!message.isDraft) {
					PS.debug('tracking start - Event: '+omnevent+' onSubmit');
					this.callback();
				}
			}
	}),
		


	/**
	 * @deprecated
	 * @class
	 * @description Check if reciprocal requirements fullfilled and open ModalLayer
	 * */
	PS_ac_reciprocal : Class.create(
		/** @lends PageContext.PS_ac_reciprocal */	
		{
		initialize: function (elem) {
			blocked = false;	
			if(elem != null) {
				this.elem = elem;		
				$(elem).className.split(" ").each(function (c) {
					if (c.match(/^reciprocalForChiffre_.+$/)) {
						forChiffre = c.replace('reciprocalForChiffre_', '');
					}
				});
				this.elem.observe('click', this.click.bind(this, forChiffre));
			}
		},
		
		click: function(forChiffre, ev) {
			if(ev != null) ev.stop();
			blocked = true;
			Modalbox.show($('ps_modal_reciprocal_' + forChiffre), {width: 540, skin: '4', hideCloseLink: false});
			if(ev != null) ev.stop();
		},
		/** @return {boolean} If original Action gets Blocked (reciprocalLayer opens) or not */
		isBlocked: function() {
			return blocked;	
		}
	}),
	
	/**
	 * @class
	 * @description Opens a little Notifer Layer with New Message Arrived<br />
	 * is called by Helper.ajaxUpdater
	 * */
	/*newMessageArrived : Class.create(
					
		{
		initialize: function () {
			myElement = "ps_alertNewMessage";
			myHideLayer = this.hideLayer;
		},
		
		showLayer: function() {
			//new Effect.Appear(myElement, { duration:1});
			window.setTimeout("myHideLayer()", 5000);
		},
		
		hideLayer: function() {
			//new Effect.Fade(myElement, { duration:1});
		}
		
	}),
	*/

		
	/**
	 * @class
	 * @description For deleting of Messages
	 * */
	deleteOrRecoverMessages: Class.create(
		/** @lends PageContext.deleteOrRecoverMessages */			
		{
		initialize: function (ele) {
			that = this;
			that.atLeastOneChecked = false;
			if($('ps_deleteMessageForm')) {
				ele.observe('click', function(ele) {
					that.checkIfAtLeastOneChecked();
					if(that.atLeastOneChecked === true) {
						$('ps_deleteMessageForm').submit();
					} else {
						$('ps_noMessageSelected').removeClassName("ps_inv");
					}
				});
			}
			if($('ps_recoverMessageForm')) {
				ele.observe('click', function(ele) {
					that.checkIfAtLeastOneChecked();
					if(that.atLeastOneChecked === true) {
						$('ps_recoverMessageForm').submit();
					} else {
						$('ps_noMessageSelected').removeClassName("ps_inv");
					}
					
				});
			}
		},
		
		checkIfAtLeastOneChecked: function() {
			that.atLeastOneChecked = false;
			$$('.ps_singleCheckbox').each(function(ele) {
				if(ele.checked) {
					that.atLeastOneChecked = true;
				}
			});
		}
		
	})    
};
//********************************************************* /PageContext ************************************************************
//*************************************************************************************************************************************

var PS_tailoredMessage = Class.create({
	initialize: function (ele) {
		this.ele = $(ele);
		if (this.ele.getElementsBySelector('a').length > 0) {
			this.ele.style.cursor = 'pointer';
			this.linkTarget = this.ele.getElementsBySelector('a').first().href;
			Event.observe(this.ele, "click", this.messageClick.bindAsEventListener(this));
		}
		PS.debug("target of tailored message: " + this.linkTarget);
	},

	messageClick: function (event) {
		window.location.href = this.linkTarget;
	}
});


// -------- extension to the UI.window object to add constraints to dragging
// ---------
Position.getWindowSize = function (w) {
	var width, height;
	w = w ? w : window;
	width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);

	return {
		width: width,
		height: height
	};
};



/**
 * BEGIN former fdc_parship.js It has moved here in order to reduce http
 * requests
 */


// AJAX

function submitFormPart(element, url, errorCallback, noErrorCallback) {
	// make sure DOM is updated and cleaned from tags,scripts and whitespaces
	// before posting!
	saveFormToDOM(element.up("form"));

	// parameters = element.form.serialize( true );
	parameters = element.up("form").serialize(true);
	var tmp = '';
	if (url.indexOf('?') != -1) {
		tmp = url + '&rand=' + Helper.getAntiCache();
	}
	else {
		tmp = url + '?rand=' + Helper.getAntiCache();
	}

	new Ajax.Request(tmp, {
		method: 'post',
		onSuccess: handleErrors(errorCallback, noErrorCallback),
		parameters: parameters
	});
}

/* Just used for Setting Name Layer  - rebuild it */
function submitFormWithParameters(element, url, additionalParameters, errorCallback, noErrorCallback) {
	// make sure DOM is updated and cleaned from tags,scripts and whitespaces
	// before posting!
	var formElement = element.up("form");
	saveFormToDOM(formElement);
	parameters = formElement.serialize(true);
	
	if (!Object.isUndefined(additionalParameters)) {
		var keys = Object.keys(additionalParameters);

		for (var i = 0; i < keys.length; i++) {
			var value = additionalParameters[keys[i]];
			parameters[keys[i]] = value;
		}
	}

	// console.debug(' --> submit form with params ' + noErrorCallback );
	new Ajax.Request(url + '?rand=' + Helper.getAntiCache(), {
		method: 'post',
		onSuccess: handleErrors(errorCallback, noErrorCallback),
		parameters: parameters
	});
}

function submitFormAndFillResult(element, url, formNames, errorCallback, noErrorCallback) {
	var additionalParameters = new Object();

	if (Object.isArray(formNames)) {
		for (var i = 0; i < formNames.length; i++) {
			additionalParameters["supportedForms"] = formNames[i];
			if(typeof allInputDefaults != "undefined") allInputDefaults.clearDefaultValuesBeforeSubmit(formNames[i]);
		}
	}
	
	submitFormWithParameters(element, url, additionalParameters, errorCallback, fillFieldsInFormPart(noErrorCallback, formNames, element));
}


// --- helper methods
// -------------------------------------------------------------------------------------------------------------


function fillFieldsInFormPart(finalNoErrorCallback, formNames, element) {
	return function (response, model) {
		for (var i = 0; i < formNames.length; i++) {
			fillFieldsInForm(formNames[i], model, element);
		}
		finalNoErrorCallback(response, model);
	};
}

function fillFieldsInForm(formName, model, element) {

	var modelFormPart = model[formName];

	if (Object.isUndefined(modelFormPart)) {
		// console.debug( 'no formpart with name \'' + formName + '\' exists' );
		return;
	}

	var form = element.form;

	for (var sub in modelFormPart) {
		if (!Object.isUndefined(modelFormPart[sub]) && modelFormPart[sub] != null) {
			fillField(form, sub, modelFormPart[sub]);
		}
	}
}

function setFormPartDisplay(key, value) {
	if (Object.isUndefined(value)) {
		// console.debug( 'empty value for key \'' + key + '\'' );
		return;
	}

	// console.debug( 'ps_form_element_display_' + key, $(
	// 'ps_form_element_display_' + key ) );
	var element = $('ps_form_element_display_' + key);
	if (element == null || Object.isUndefined(element)) {
		return;
	}

	var emptyDiv = null;
	var parentDiv = element.parentNode;
	if (parentDiv != null) {
		var emptyDivs = Element.adjacent(parentDiv, 'div.ps_emptyInput');
		if (Object.isArray(emptyDivs) && emptyDivs.length > 0) {
			emptyDiv = emptyDivs[0];
		}
	}

	if (value == null || value == '') {
		if (emptyDiv != null) {
			emptyDiv.show();
		}
		element.hide();
	}
	else {
		if (emptyDiv != null) {
			emptyDiv.hide();
		}
		element.show();
		element.innerHTML = value;
	}

}

/**
 * Fills a display field in the display view with the value of the corresponding
 * input field in the edit view.<br/> <br/> If the inputfield is of type select
 * the option list will be searched for an option with the correct value and the
 * displayed value will be the text of this option.<br/> <br/> In case of
 * checkbox or radio buttons the list of all inputfields will be searched for
 * the right element and the value to display will be the label of the
 * inputefield. In case of checkbox the labels of multiple selected checkboxes
 * will be joined with an '<code>, </code>'.
 * 
 * @param form
 *            the form containing the inputfields
 * @param key
 *            the <code>name</code> of the inputfield
 * @param value
 *            the value which comes from the response for this field
 * 
 * @author Max Scheffler
 */

function fillField(form, key, value) {
	var formElement = form[key];
	if (!formElement) {
		return;
	}
	// The only way to tell apart a NodeList from a Node which works in ie and
	// ff is to ducktype the formElement
	if (isNodeList(formElement)) {
		var newValueArray = new Array();
		// p.e. elements of a radiobutton-group
		for (var i = 0; i < formElement.length; i++) {
			var item = formElement[i];
			if (Object.isArray(value)) {
				for (var j = 0; j < value.length; j++) {
					if (item.value == value[j]) {
						newValueArray.push($(item.id + "_label").innerHTML.strip());
					}
				}

			}
			else if (item.value == value) {
				newValueArray.push($(item.id + "_label").innerHTML);
			}
			// HACK HACK HACK HACK to save posted value(s) and true checked in
			// the DOM
			if (item.checked) {
				item.setAttribute("checked", "checked");
			}
			else if (item.hasAttribute("checked")) {
				item.removeAttribute("checked");
			}
			// End HACK
		}

		value = newValueArray.join(", ");
	}
	else {
		if (!formElement.nodeName) {
			return;
		}

		if (formElement.nodeName.toLowerCase() == 'input' && formElement.type.toLowerCase() != 'text') {
			return;
		}
		// HACK HACK HACK HACK to save posted value(s) and true checked in the
		// DOM
		else if (formElement.nodeName.toLowerCase() == 'input' && formElement.type.toLowerCase() == 'text') {
			formElement.setAttribute("value", value);
		}
		// End HACK
		if (formElement.nodeName.toLowerCase() == 'select') {
			var options = formElement.options;

			for (var i = 0; i < options.length; i++) {
				if (value == options[i].value && options[i].value != '') {
					value = options[i].text;
					// HACK HACK HACK HACK to save posted value(s) and true checked
					// in the DOM
					options[i].setAttribute("selected", "selected");
				}
				else {
					options[i].removeAttribute("selected");
				}
				// End HACK
			}
		}
	}


	setFormPartDisplay(key, value.toString().escapeHTML());
}

/**
 * The ie is unable to test whether or not the object is a NodeList. This test
 * can determine whether an object is a NodeList or a NodeElement.<br />
 * <br />
 * ATTANTION: it can check for NodeList or NodeElement only!
 * 
 * @param object
 *            the object to test this object needs to be a NodeList or a
 *            NodeElement
 * @return true if the given object is an NodeList and false if it's a
 *         NodeElement
 * 
 * @author Max Scheffler
 */

function isNodeList(object) {
	return (typeof object.length == 'number' && Object.isUndefined(object.nodeName));
}

function fillErrors(object, path) {
	// PS.debug("1: " + object + " - " + $( path ));
	if (!Object.isArray(object)) {
		for (var sub in object) {
			if (path == '') {
				fillErrors(object[sub], sub);
			}
			else {
				fillErrors(object[sub], path + '_' + sub);
			}
		}
	}
	else {
		// PS.debug(object + " - " + $( path ));
		var errorBox = $(path);
		var errorText = '';

		for (var i = 0; i < object.length; i++) {
			errorText = errorText + '<p>' + object[i] + '</p>';
			if (i != object.length - 1) {
				errorText = errorText + "<br/>";
			}
		}

		if (errorText.length > 0) {
			errorBox.up('.ps_subcolumns').addClassName('ps_hasError');
			errorBox.down('div.ps_errorText').update(errorText);
			errorBox.show();
		}
	}
}

/**
 * Analyses the errors in the response filed in by the JSONView and tries to
 * find errorboxes in which the errors could be written.<br/> <br/> If any
 * error occured the errorCallback will be invoced otherwise the noErrorCallback
 * will be invoced.</br> <br/> If you want to use this mechanism you have to
 * use the [@ajaxAwareErrorBox] as the error box.
 * 
 * @param errorCallback
 *            this function will be invoced if an error occured. The function
 *            must look like <code>function( response, model ){ ... }</code>
 * @param noErrorCallback
 *            this function will be invoced if no error occured. The function
 *            must look like <code>function( response, model ){ ... }</code>
 * 
 * @author Max Scheffler
 */

function handleErrors(errorCallback, noErrorCallback) {
	// PS.debug("vv" + errorCallback + "noerror: " + noErrorCallback);
	return function (response) {

		var model = response.responseText.evalJSON();
		var errorBoxes = $$('.ps_errorbox');
/*
		 * We have 2 differnet errorBox Types (spelling) "ps_errobox" are the
		 * old errortypes (no genBox stuff) "ps_errorBox" new errortypes with
		 * genBox stuff - do not delete all this with .innerHTML When all
		 * errorBoxes are the same (errorBox!) we can delete this workaround.
		 */
		errorBoxes.each(function (errorBox) {
			errorBox.innerHTML = '';
			errorBox.hide();
		});
		var errorBoxes = $$('.ps_errorBox');
		errorBoxes.each(function (errorBox) {
			errorBox.hide();
		});
		if (Object.isUndefined(model.$errors) || Object.keys(model.$errors).length == 0) {
			noErrorCallback(response, model);
			Par.Helper.publishEvent("Par:PageContext:action:personalDataSaved", {"onElement": "personalDataForm"});
			return;
		}
		errorCallback(response, model);
		fillErrors(model.$errors, 'ps_error_box');
	};
}

// end posting whole form
/**
 * Helper function for saving form element values, select and checked states to
 * the DOM
 * 
 * @param form
 *            the form containing the input fields (form can be string integer
 *            or object)
 * @param elm
 *            a/the specific element to update if null whole form updates to the
 *            DOM
 * 
 * @author Magnus Pettersson
 */

function saveFormToDOM(form, elm) {
	// check for valid input else return null
	if (typeof(form) === 'undefined' && document.forms[form] == 'undefined') {
		return;
	}
	else {
		if (typeof(form) == 'number') {
			form = document.forms[form.toString];
		}
		else if (typeof(form) == 'string') {
			form = document.forms[form];
		}
		// else treat form as an object
	}

	// declare functions only available in this local scope
	var setA = function (o, a, v) {
		o.setAttribute(a, v);
	};
	var remA = function (o, a) {
		o.removeAttribute(a);
	};
	var remW = function (s) {
		//return s.replace(new RegExp("^[//s]+$", "g"), "");
		return s.replace(new RegExp("^\\s*$", "g"), "");
	};


	// loop trough the form elements
	for (var i = 0; i < form.elements.length; i++) {
		var obj = form.elements[i];

		// om def och string och pa = pa
		if (typeof(elm) !== 'undefined' && typeof(elm) == 'string' && obj.getAttribute('name') != elm) {
			continue;
		}

		var strT = obj.type.toLowerCase();

		// if checkbox or radio
		if (strT == 'checkbox' || strT == 'radio') {
			if (obj.checked == true) {
				setA(obj, 'checked', 'checked');
			}
			else {
				remA(obj, 'checked');
			}
		}

		// if text (hidden can be added here at a later time if needed)
		if (strT == 'text') {
			obj.value = remW(obj.value.stripScripts().stripTags());
			setA(obj, 'value', obj.value);
		}

		// if textarea (cleaning whitespaces and updating both textarea
		// innerHTML and value attribute in the DOM)
		if (strT == 'textarea') {
			obj.value = remW(obj.value.stripScripts().stripTags());
			setA(obj, 'value', obj.value);
			obj.innerHTML = obj.value;
		}

		// if select box (works with single and multiple selections)
		if (strT == 'select-one' || strT == 'select-multiple') {
			for (var j = 0; j < obj.options.length; j++) {
				var objC = obj.options[j];
				if (objC.selected == true) {
					setA(objC, 'selected', 'selected');
				}
				else {
					remA(objC, 'selected');
				}
			}
		}
	}
}

/**
 * END former fdc_parship.js
 */

/** 
 * Begin Modalbox
 */
// TODO: refactor - only used once when initializing Modalbox
// script.aculo.us builder.js v1.7.1_beta3, Fri May 25 17:19:41 +0200 2007
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us,
// http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style
// license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
/**
 * @ignore
 */
var Builder = {
	NODEMAP: {
		AREA: 'map',
		CAPTION: 'table',
		COL: 'table',
		COLGROUP: 'table',
		LEGEND: 'fieldset',
		OPTGROUP: 'select',
		OPTION: 'select',
		PARAM: 'object',
		TBODY: 'table',
		TD: 'table',
		TFOOT: 'table',
		TH: 'table',
		THEAD: 'table',
		TR: 'table'
	},
	// note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
	// due to a Firefox bug
	node: function (elementName) {
		elementName = elementName.toUpperCase();

		// try innerHTML approach
		var parentTag = this.NODEMAP[elementName] || 'div';
		var parentElement = document.createElement(parentTag);
		try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
			parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
		}
		catch (e) {}
		var element = parentElement.firstChild || null;

		// see if browser added wrapping tags
		if (element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0];

		// fallback to createElement approach
		if (!element) element = document.createElement(elementName);

		// abort if nothing could be created
		if (!element) return;

		// attributes (or text)
		if (arguments[1]) if (this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) {
			this._children(element, arguments[1]);
		}
		else {
			var attrs = this._attributes(arguments[1]);
			if (attrs.length) {
				try { // prevent IE "feature":
					// http://dev.rubyonrails.org/ticket/2707
					parentElement.innerHTML = "<" + elementName + " " + attrs + "></" + elementName + ">";
				}
				catch (e) {}
				element = parentElement.firstChild || null;
				// workaround firefox 1.0.X bug
				if (!element) {
					element = document.createElement(elementName);
					for (attr in arguments[1])
					element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
				}
				if (element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0];
			}
		}

		// text, or array of children
		if (arguments[2]) this._children(element, arguments[2]);

		return element;
	},
	_text: function (text) {
		return document.createTextNode(text);
	},

	ATTR_MAP: {
		'className': 'class',
		'htmlFor': 'for'
	},

	_attributes: function (attributes) {
		var attrs = [];
		for (attribute in attributes)
		attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/, '&quot;') + '"');
		return attrs.join(" ");
	},
	_children: function (element, children) {
		if (children.tagName) {
			element.appendChild(children);
			return;
		}
		if (typeof children == 'object') { // array can hold nodes and text
			children.flatten().each(function (e) {
				if (typeof e == 'object') element.appendChild(e);
				else if (Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e));
			});
		}
		else if (Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children));
	},
	_isStringOrNumber: function (param) {
		return (typeof param == 'string' || typeof param == 'number');
	},
	build: function (html) {
		var element = this.node('div');
		$(element).update(html.strip());
		return element.down();
	},
	dump: function (scope) {
		if (typeof scope != 'object' && typeof scope != 'function') scope = window; // global
		// scope
		var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX " + "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P " + "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD " + "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);

		tags.each(function (tag) {
			scope[tag] = function () {
				return Builder.node.apply(Builder, [tag].concat($A(arguments)));
			};
		});
	}
};


/*
	 * ModalBox - The pop-up window thingie with AJAX, based on prototype and
	 * script.aculo.us. Doku & Wiki: http://code.google.com/p/modalbox/w/list
	 * Copyright Andrey Okonetchnikov (andrej.okonetschnikow@gmail.com),
	 * 2006-2007 All rights reserved.
	 * 
	 * VERSION 1.5.4 Last Modified: 07/16/2007
	 */

/**
 * @ignore yyyy
 */
if (!window.Modalbox) var Modalbox = new Object();
Modalbox.Methods = {
	focusableElements: new Array,
	options: {
		title: "",// Title of the ModalBox window
		overlayClose: false, // Close modal box by clicking on overlay
		width: 500,	// Default width in px
		height: 200,// Default height in px
		overlayOpacity: .3,	// Default overlay opacity
		overlayDuration: 0, // Default overlay fade in/out duration in seconds
		slideDownDuration: 0, // Default Modalbox appear slide down effect in seconds
		slideUpDuration: 0, // Default Modalbox hiding slide up effect in seconds
		resizeDuration: .10,// Default resize duration seconds
		inactiveFade: true,	// Fades MB window on inactive state
		loadingString: "", //Please wait. Default loading string message (Loading...)
		hideCloseLink: false,
		confirmBeforeClosing: false,
		closeString: "",//Close window Default title attribute for close window link
		params: {},
		method: 'get', // Default Ajax request method
		skin: '1',
		chapter: '', // set focus on chapter
		top: null // top Position of MB 
	},
	_options: new Object,

	setOptions: function (options) {
		Object.extend(this.options, options || {});
	},

	_init: function (options) {
		// Setting up original options with default options
		Object.extend(this._options, this.options);
		this.setOptions(options);
		// Create the overlay
		this.MBoverlay = Builder.node("div", {
			id: "MB_overlay"
		});
		// Create the window
		this.MBwindow = Builder.node("div", {
			id: "MB_window",
			style: "display: none",
			className: "parship ps_modalWindowSkin" + this.options.skin
		}, [
		this.MBinnerOverlay = Builder.node("div", {
			id: "MB_innerOverlay",
			style: "display: none"
		}),
		this.MBframe = Builder.node("div", {
			id: "MB_frame"
		}, [
		this.MBheader = Builder.node("div", {
			id: "MB_header"
		}, [
		this.MBcaption = Builder.node("h2", {
			id: "MB_caption"
		}), this.MBclose = Builder.node("a", {
			id: "MB_close",
			title: this.options.closeString,
			href: "#",
			style: "display:none"
		}, [
		Builder.build("<span>&times;</span>") ]) ]), this.MBcontent = Builder.node("div", {
			id: "MB_content"
		}, [
		this.MBloading = Builder.node("div", {
			id: "MB_loading"
		}, this.options.loadingString) ]) ]) ]);

		// Inserting into DOM
		document.body.insertBefore(this.MBwindow, document.body.childNodes[0]);
		document.body.insertBefore(this.MBoverlay, document.body.childNodes[0]);

		// IE doesn't allow setOpacity on the Builder element before placement
		$('MB_overlay').setOpacity(this.options.overlayOpacity);
		$('MB_innerOverlay').setOpacity(this.options.overlayOpacity);
		
		// Initial scrolling position of the window. To be used for remove
		// scrolling effect during ModalBox appearing
		this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
		this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;

		// Adding event observers
		this.hide = this.hide.bindAsEventListener(this);
		this.close = this._hide.bindAsEventListener(this);
		this.kbdHandler = this.kbdHandler.bindAsEventListener(this);
		this._initObservers();

		this.initialized = true;
		this.confirmCloseDialogActive = false;
		this.active = true;
		this.contentAnchor = "";
		this.usesDomNode = false;

	},

	show: function (content, options) {
		
		if(options.top == null) {
			$$('body')[0].scrollTo();
		}
		
		if (!this.initialized)
			this._init(options);
		
		this.content = content;
		this.setOptions(options);

		Element.update(this.MBcaption, this.options.title);

		if (this.options.hideCloseLink) {
			$('MB_close').hide();
		} else {
			$('MB_close').show();
			$('MB_close').blur();
		}
		
		if (this.MBwindow.style.display == "none") {
			this._appear();
			this.event("onShow");
		} else {
			this._update();
			this.event("onUpdate");
		}
		//this.focusableElements = this._findFocusableElements();
		//this._moveFocus();
	},

	hide: function (options) {		
		if (this.options.confirmBeforeClosing && !this.confirmCloseDialogActive) {
			if (typeof this.options.confirmBeforeClosing == 'boolean')
				return this.showClosingConfirmation();
			if (typeof this.options.confirmBeforeClosing == 'function' && this.options.confirmBeforeClosing())
				return this.showClosingConfirmation();
		}
			
		this.event('beforeHide', true);

		if (this.initialized) {
			if (options)
				Object.extend(this.options, options);
			$(this.MBwindow).hide();
			this._deinit();
			this.event('afterHide', true);
		} else throw ("Modalbox isn't initialized");
	},

	_hide: function (event) {
		if (event)
			Event.stop(event);
		this.hide();
	},
	
	showClosingConfirmation: function() {
		if (!$('MB_confirmCloseDialog'))
			return false;
		// reinsert confirmation modal higher in the hierarchy as a sibling of the inner
		// overlay to eliminate the IE6 & 7 z-index bug
		if ( $('MB_confirmCloseDialog').descendantOf('MB_content') ) {
			this.MBwindow.insert({ top: $('MB_confirmCloseDialog').remove() });
		}
		
		this.MBinnerOverlay.show();
		this.MBinnerOverlay.setStyle({ height: this.MBwindow.getHeight() + 'px' });
		$('MB_confirmCloseDialog').show().setStyle({visibility: 'visible'});
		this.confirmCloseDialogActive = true;
	},
	
	hideClosingConfirmation: function() {
		if (!$('MB_confirmCloseDialog'))
			return false;
		this.MBinnerOverlay.hide();
		$('MB_confirmCloseDialog').hide();
		this.confirmCloseDialogActive = false;
	},

	_appear: function () { // First appearing of MB
		this._toggleSelects();
		this._setOverlay();
		this._setWidth();
		this._setPosition();
		this.MBwindow.setStyle({
			display: 'block',
			visibility: 'hidden'
		});

		this.loadContent();

		this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
		Event.observe(window, "resize", this._setWidthAndPosition);

		this.MBwindow.setStyle({
			visibility: 'visible'
		});
	},

	fitModalWidthToElement: function () {
		if (this.MBcontent.down('.ps_fitModalWidthToThis')) {
			var currentWindowWidth		= this.MBwindow.getWidth();
			var relevantElement 		= this.MBcontent.down('.ps_fitModalWidthToThis');
			var relevantElementWidth 	= 0;
			
			// accomodate hidden elements that technically do not have a width, but have a width style
			if (relevantElement)
				relevantElementWidth = relevantElement.getWidth() > 0 ? relevantElement.getWidth() : parseInt(relevantElement.getStyle('width'));
			
			if (relevantElementWidth > 0) {
				var newWidth = relevantElementWidth + $(this.MBheader).getHeight();
				this.MBwindow.setStyle({
					width: (newWidth) + 'px'
				});
				this.options.width = newWidth;
				PS.debug('overriding modal width: element with .ps_fitModalWidthToThis forces a width of ' + newWidth + 'px');
				this._setPosition();
			}
		}
	},

	unhideContent: function () {
		this.MBcontent.down().setStyle({
			visibility: 'visible'
		});
	},

	resize: function (byWidth, byHeight, options) { // Change size of MB without loading content
		if (byWidth < 5 && byWidth > -5) byWidth = 0;
		if (byHeight < 5 && byHeight > -5) byHeight = 0;

		var oWidth = $(this.MBoverlay).getWidth();
		var wHeight = $(this.MBwindow).getHeight();
		var wWidth = $(this.MBwindow).getWidth();
		var hHeight = $(this.MBheader).getHeight();
		var cHeight = $(this.MBcontent).getHeight();
		var newHeight = ((wHeight - hHeight + byHeight) <= cHeight) ? (cHeight + hHeight) : (wHeight + byHeight);
		var newWidth = wWidth + byWidth;
		
		this.options.width = newWidth;
		if (options)
			this.setOptions(options);
		new Effect.ScaleBy(this.MBwindow, byWidth, byHeight, {
			duration: this.options.resizeDuration,
			afterFinish: function() { this.event("afterResize"); }.bind(this)
		});
	},
	
	autoresizeHeight: function () {
		var newHeight 	= $(this.MBheader).getHeight() + $(this.MBcontent).getHeight();
		
		$(this.MBwindow).setStyle({height: newHeight + 'px'});
	},

	/**
	 * @description reuses an existing modal with new content 
	 */
	_update: function () {
		this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];

		// make sure we the new content isn't a node located inside the current content
		// and wiped out by accident
		if (typeof this.content == 'object') {
			if (this.content.descendantOf('MB_content'))
				this.content = this.content.innerHTML;
		}
		
		this._moveContentBack();
		Element.update(this.MBcontent, "");
		this.MBcontent.appendChild(this.MBloading);
		Element.update(this.MBloading, this.options.loadingString);
		this._loadAfterResize();
	},

	/**
	 * loads this.content as either a string of HTML, a URI or a DOMElement
	 */
	loadContent: function () {
		if (!this.event("beforeLoad"))
			return;
		
		if (typeof this.content == 'string') {
			var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
			
			if (htmlRegExp.test(this.content)) {
				this._insertContent(this.content);
				this.fitModalWidthToElement(); 
				this.unhideContent();
				
			} else {
				new Ajax.Request(this.content, {
					method: this.options.method.toLowerCase(),
					parameters: this.options.params,
					onComplete: function (transport) {
						
						var response = new String(transport.responseText);
						
						response.extractScripts().map(function (script) {
							return eval(script.replace("<!--", "").replace("// -->", ""));
						}.bind(window));
						
						this._insertContent(transport.responseText.stripScripts());
						this.fitModalWidthToElement();
						
						Helper.applyClassHandlers(PSDom.methodMap, document.getElementById("MB_content"));
						
						this.unhideContent();
					}.bind(this)
				});
			}
		} else if (typeof this.content == 'object') {
			this._insertContent(this.content);
			this.fitModalWidthToElement(); 
			this.unhideContent();
			
		} else {
			Modalbox.hide();
			throw ('Please specify correct URL or HTML element (plain HTML or object)');
		}
	},

	_insertContent: function (content) {		
		this.usesDomNode = false;
		Element.extend(this.MBcontent);
		this.MBcontent.update("");
		
		if (typeof content == 'string') { //from an Page loaded via Ajax
			this.MBcontent.hide().update(content);
			if (this.MBcontent.down('.modal_title')) {
				Element.update(this.MBcaption, this.MBcontent.down('.modal_title').innerHTML);
				this.MBcontent.down('.modal_title').hide();
			} 
			if (this.MBcontent.down('#parship') && this.MBcontent.down('#ps_main')) { //If these ids occur in a modal-snippet something went wrong
				//location.href = this.content;
				this.MBcontent.down("#parship").hide();
				$("MB_caption").innerHTML = "Error";
				$("ps_sessionError").show();
				//does not really help for bug-3394
			}
			this.resizeModalBoxToContent();
		} else if (typeof this.content == 'object') { //HTML-Snippet included to page
			this.usesDomNode = true;

			// save the frame element of the content block so we
			// can write the block back to its original position
			// later when closing the modal
			this.contentAnchor = this.content;

			// try to get the window title from an element defined
			// within the content block - this way we can define it
			// once instead of again and again in each trigger link / button
			if (this.content != null && this.content.id != null) {
				if ($(this.content.id + "_title")) {
					Element.update(this.MBcaption, $(this.content.id + "_title").innerHTML);
					$(this.content.id + "_title").hide();
				} else if (this.content.down('.modal_title')) {
					Element.update(this.MBcaption, this.content.down('.modal_title').innerHTML);
					this.content.down('.modal_title').hide();
				}
			}

			// move the content block out of its frame element into the modal
			this.MBcontent.update(this.content.firstDescendant());
			this.MBcontent.down().show();
			this.MBcontent.down().setStyle({
				visibility: 'hidden'
			});
			this.resizeModalBoxToContent();
		
		
		
		// Height is defined. Creating a scrollable window
		// WARNING: this path is broken, at least on IE7 - produces negative
		// window heights
		// and throws an argument error in the process
		// don't set fixed heights as a workaround
		} else {
			this._setWidth();
			var newHeight = (Element.getHeight(this.MBwindow) - Element.getHeight(this.MBheader)) + 'px';
			this.MBcontent.setStyle({
				overflow: 'auto',
				height: newHeight
			});
			this.MBcontent.show();
			this.focusableElements = this._findFocusableElements();			
			this._moveFocus();
			this.event("afterLoad");
		}
	},

	resizeModalBoxToContent: function(){
		// Prepare and resize modal box for content
		if (this.options.height == this._options.height) {
			Modalbox.resize(0, 
				this.MBcontent.getHeight() - Element.getHeight(this.MBwindow) + Element.getHeight(this.MBheader), {
					afterResize: function () {
						this.MBcontent.show();
						
						// go to chapter is set
						if(this.options.chapter == ''){
							this.focusableElements = this._findFocusableElements();
							this._moveFocus();
						}
						else {
							$(this.options.chapter).scrollIntoView(true);
							window.scrollTo(0, 0);
						}
						this.event("afterLoad");
				}.bind(this)
			});
		}
	},
	
	activate: function (options) {
		this.setOptions(options);
		this.active = true;
		
		Event.observe(this.MBclose, "click", this.close);
		
		if (this.options.overlayClose)
			Event.observe(this.MBoverlay, "click", this.hide);
		
		Element.show(this.MBclose);
		
		if (this.options.inactiveFade)
			new Effect.Appear(this.MBwindow, { duration: this.options.slideUpDuration });
	},

	deactivate: function (options) {
		this.setOptions(options);
		this.active = false;
		
		Event.stopObserving(this.MBclose, "click", this.close);
		
		if (this.options.overlayClose)
			Event.stopObserving(this.MBoverlay, "click", this.hide);
		
		Element.hide(this.MBclose);
		
		if (this.options.inactiveFade)
			new Effect.Fade(this.MBwindow, { duration: this.options.slideUpDuration, to: .75 });
	},

	_initObservers: function () {
		Event.observe(this.MBclose, "click", this.close);
		
		if (this.options.overlayClose)
			Event.observe(this.MBoverlay, "click", this.hide);
		
		Event.observe(document, "keypress", Modalbox.kbdHandler);
	},

	_removeObservers: function () {
		Event.stopObserving(this.MBclose, "click", this.close);
		
		if (this.options.overlayClose)
			Event.stopObserving(this.MBoverlay, "click", this.hide);
		
		Event.stopObserving(document, "keypress", Modalbox.kbdHandler);
	},

	_loadAfterResize: function () {
		this._setWidth();
		this._setPosition();
		this.loadContent();
	},

	_moveFocus: function () {
		if (this.focusableElements.length > 0) {			
			// IE might for some reason complain about trying to give focus to an invisible element
			try {
				this.focusableElements.first().focus();				
			} catch (e) {}
			
		} else if ($("MB_close") && $("MB_close").visible())
			$("MB_close").focus();
	},

	_findFocusableElements: function () {
		return $A($("MB_content").descendants()).findAll(function (node) {
			return (["INPUT", "TEXTAREA", "SELECT", "A", "BUTTON"].include(node.tagName));
		});
	},

	kbdHandler: function (e) {		
		var node = Event.element(e);
		switch (e.keyCode) {
		case Event.KEY_TAB:
			if (Event.element(e) == this.focusableElements.last()) {
				Event.stop(e);				
				this._moveFocus();
			}
			break;
		case Event.KEY_ESC:
			if (this.active && !this.options.hideCloseLink) this._hide(e);
			break;
		case 32:
			this._preventScroll(e);
			break;
		case 0:
			// For Gecko browsers compatibility
			if (e.which == 32) this._preventScroll(e);
			break;
		case Event.KEY_UP:
		case Event.KEY_DOWN:
		case Event.KEY_PAGEDOWN:
		case Event.KEY_PAGEUP:
		case Event.KEY_HOME:
		case Event.KEY_END:
			// Safari operates in slightly different way. This realization
			// is still buggy in Safari.
			if (/Safari|KHTML/.test(navigator.userAgent) && !["textarea", "select"].include(node.tagName.toLowerCase())) Event.stop(e);
			else if ((node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a")) Event.stop(e);
			break;
		}
	},

	_preventScroll: function (event) { // Disabling scrolling by "space" key
		if (!["input", "textarea", "select", "button"].include(Event.element(event).tagName.toLowerCase())) Event.stop(event);
	},

	_deinit: function () {
		this._toggleSelects();
		this._removeObservers();
		
		Event.stopObserving(window, "resize", this._setWidthAndPosition);

		$(this.MBoverlay).hide();
		this._removeElements();
	},

	_removeElements: function () {
		if (navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("", "");
			window.scrollTo(this.initScrollX, this.initScrollY);
		}
		
		Element.remove(this.MBoverlay);
		
		this._moveContentBack();
		Element.remove(this.MBwindow);
		this.initialized = false;
		this.event("afterHide");
		this.setOptions(this._options);
	},

	/**
	 * write the modal content block back to its original frame in the page
	 * (provided we didn't pull the content in elsewhere)
	 */
	_moveContentBack: function () {
		if (this.usesDomNode) {
			$(this.contentAnchor).update(this.MBcontent.firstDescendant());
			this.contentAnchor.down().hide();
		}
	},

	_setOverlay: function () {
		if (navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("100%", "hidden");
			if (!navigator.appVersion.match(/\b7.0\b/))
				window.scrollTo(0, 0);
		}
	},

	_setWidth: function () {
		Element.setStyle(this.MBwindow, { width: this.options.width + "px" });
	},

	_setPosition: function () {
		this.MBwindow.style.left = Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2) + "px";
		
		if(this.options.top != null){
			this.MBwindow.style.top = this.options.top + "px";
		}	
	},

	_setWidthAndPosition: function () {
		this._setWidth();
		this._setPosition();
	},

	_getScrollTop: function () { 
		// From: http://www.quirksmode.org/js/doctypes.html		
		var theTop;
		
		if (document.documentElement && document.documentElement.scrollTop)
			theTop = document.documentElement.scrollTop;
		else if (document.body)
			theTop = document.body.scrollTop;
		return theTop;
	},
	
	// IE requires height to 100% and overflow hidden (taken from lightbox)
	_prepareIE: function (height, overflow) {
		var body = document.getElementsByTagName('body')[0];
		body.style.height = height;
		var html = document.getElementsByTagName('html')[0];
		html.style.height = height;
	},
	
	_toggleSelects: function () {
		if (navigator.appVersion.match(/\bMSIE\b/))
			$$("select").each(function (select) {
				select.style.visibility = (select.style.visibility == "") ? "hidden" : "";
			});
	},
	
	event: function (eventName, keepAfterExecution) {
		if (this.options[eventName]) {
			var returnValue = this.options[eventName]();
			
			if (!keepAfterExecution)
				this.options[eventName] = null;
			
			if (returnValue != undefined)
				return returnValue;
		}
		
		return true;
	},
	
	//can be called from outside to set a new Skin
	setSkin: function(newSkin) { 
		var cn = $('MB_window').className.split(' ');
		var i = 0;
		var prefix = 'ps_modalWindowSkin';
		while (i < cn.length) {
			if (cn[i].startsWith(prefix)) {
				skinNo = cn[i].substring(prefix.length, cn[i].length);
			}
			i++;
		}
		$('MB_window').removeClassName('ps_modalWindowSkin' + skinNo);
		$('MB_window').addClassName('ps_modalWindowSkin' + newSkin);
	}
};

Object.extend(Modalbox, Modalbox.Methods);

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
	initialize: function (element, byWidth, byHeight, options) {
		this.element = $(element);
		var options = Object.extend({
			scaleFromTop: true,
			scaleMode: 'box',
			// 'box' or 'contents' or {} with provided
			// values
			scaleByWidth: byWidth,
			scaleByHeight: byHeight
		}, arguments[3] || {});
		this.start(options);
	},
	setup: function () {
		this.elementPositioning = this.element.getStyle('position');

		this.originalTop = this.element.offsetTop;
		this.originalLeft = this.element.offsetLeft;

		this.dims = null;
		if (this.options.scaleMode == 'box') this.dims = [this.element.offsetHeight, this.element.offsetWidth];
		if (/^content/.test(this.options.scaleMode)) this.dims = [this.element.scrollHeight, this.element.scrollWidth];
		if (!this.dims) this.dims = [this.options.scaleMode.originalHeight, this.options.scaleMode.originalWidth];

		this.deltaY = this.options.scaleByHeight;
		this.deltaX = this.options.scaleByWidth;
	},
	update: function (position) {
		var currentHeight = this.dims[0] + (this.deltaY * position);
		var currentWidth = this.dims[1] + (this.deltaX * position);

		this.setDimensions(currentHeight, currentWidth);
	},

	setDimensions: function (height, width) {
		var d = {};
		d.width = width + 'px';
		d.height = height + 'px';

		var topd = Math.round((height - this.dims[0]) / 2);
		var leftd = Math.round((width - this.dims[1]) / 2);
		if (this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
			if (!this.options.scaleFromTop) d.top = this.originalTop - topd + 'px';
			d.left = this.originalLeft - leftd + 'px';
		}
		else {
			if (!this.options.scaleFromTop) d.top = -topd + 'px';
			d.left = -leftd + 'px';
		}
		
		if (width < 0 || height < 0)
			return;
		
		this.element.setStyle(d);
	}
});

/** 
 * END Modalbox
 */


/** @namespace Par-Namspace Parship Core-Namespace */
var Par = {

	/**
	 * Deliberately non-Prototype configuration object
	 * Code is duplicated under common/javascript/psconf.ftl for use 
	 * in landing pages without parship.js (macros.ftl:@loadJsConfigFromSuperoperty)
	 */
	/** @namespace Conf-Namspace Getting and Setting of Page-Configuration */
	Conf : {
		props: {},
		add: function add(key, value) {
			this.props[key] = value;
			if (typeof console === "undefined" || typeof console.debug === "undefined") { return false; }
			//console.debug("Added {" + key +" : " + value + "} to Par.Conf.props");
		},
		get: function get(key) {
			return this.props[key];
		},
		exists: function exists(key) {
			return typeof this.props[key] !== 'undefined';
		}

	},


	//********************************************************* Inits **********************************************************
	//***************************************************************************************************************************
	/** @namespace Inits-Namspace Setting configurations and preparing the DOM */
	Inits : {
		/**
		 * @class
		 * @description Set initial Configuration
		 */
		confInit: function confInit() {
			try {
				Par.Conf.add('isDevSystem',  window.location.host.endsWith('parship.office') || window.location.host.endsWith('parship.net') || window.location.host.indexOf('localhost') != -1 ? true : false);
				Par.Conf.add('forceDebug', window.location.search.indexOf('jsDebug=true') != "-1" ? true : false);
			} catch (e) {
				Par.debug("Error in Par.Inits.confInit: " + e, "error");
			}
		},
		
		/**
		 * @class
		 * @description Look for Nodes in the DOM that need to have some Mojo!
		 */
		domInit: function domInit() {
			try {
				//Helper.domPrototyping(); //Prototype JS-Objects
				
				if($$('[data-trigger]')[0]) { //Attribute: trigger
					Par.Helper.subscribeEvent("Par:Inits:domInit:preventDoubleSubmit", function(data) {
						var message = data.memo;
						//var data2 = data.myArgs;
						//Par.debug($j(data.onElement).attr("data-trigger"));
						Par.Helper.preventDoubleSubmit.init(message);
						//Par.Helper.preventDoubleSubmit._stopEvent();
					});
					
					
					Par.Helper.subscribeEvent("Par:Inits:domInit:ps_loginBox", function(data) {
						//var message = data.memo;
						//alert(data.memo.onElement);
						var walla = new Par.PageContext.secureLogin(data);
						//alert(walla.doYadda("external"));
						//alert(walla._doStuff("external"));//internal undefined
					});

					Par.Helper.subscribeEvent("Par:Inits:domInit:editElementMaritalStatus", function(data) {
						Par.PageContext.editMaritalStatus.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:editElementSmoker", function(data) {
						Par.PageContext.editSmoker.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:editElementBodyType", function(data) {
						Par.PageContext.editBodyType.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:editElementSport", function(data) {
						Par.PageContext.editSport.init(data);
					});
					
					Par.Helper.subscribeEvent("Par:Inits:domInit:partnerNoteForm", function(data) {
						Par.PageContext.partnerNoteForm.init(data);
					});
					
					Par.Helper.subscribeEvent("Par:Inits:domInit:imageReleaseModal", function(data) {
						Par.PageContext.imageReleaseModal.init(data);
					});
					
					Par.Helper.subscribeEvent("Par:Inits:domInit:viewStatusUpdate", function(data) {
						Par.PageContext.viewStatusUpdate.init(data);
					});
					
									
					//init all tabs on partner Page
					Par.Helper.subscribeEvent("Par:Inits:domInit:partnerProfileTabs", function(data) {
						var myProfileTabsOption = Object.extend({}, data);
						myProfileTabsOption = Object.extend(myProfileTabsOption, {"onPage":"partnerProfile"});
						Par.PageContext.profileTabs.init(myProfileTabsOption);
					});
					//init all tabs on my Page
					Par.Helper.subscribeEvent("Par:Inits:domInit:myProfileTabs", function(data) {
						var myProfileTabsOption = Object.extend({}, data);
						myProfileTabsOption = Object.extend(myProfileTabsOption, {"onPage":"myProfile"});
						Par.PageContext.profileTabs.init(myProfileTabsOption);
					});
					
					//Fired after a Tab has been loaded on profilePage
					Par.Helper.subscribeEvent("Par:Inits:domInit:tabLoaded", function(data) {
						Par.PageContext.profileTabs.initAjaxDom(data);
						/*if($('ps_aboutTabContent') != null && $('ps_aboutTabContent').getAttribute("data-currentOpenQuestion") != null) {
							Helper.saveAndEditQuestions.editQuestion($('ps_aboutTabContent').getAttribute("data-currentOpenQuestion"), false, Par.PageContext.editTabAboutMe.editQuestion);
						}*/
						
					});
					
					Par.Helper.subscribeEvent("Par:Inits:domInit:partnerAlias", function(data) {
						new Par.PageContext.partnerAlias.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:editFavorite", function(data) {
						new Par.PageContext.editFavorite.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:matchingResultGraphic", function(data) {
						new Par.PageContext.matchingResultGraphic.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:showNotice", function(data) {
						new Par.PageContext.showNotice.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:toggleSelectbox", function(data) {
						new Par.PageContext.toggleSelectbox.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:personalStatementView", function(data) {
						new Par.PageContext.personalStatementView.init(data);
					});
					Par.Helper.subscribeEvent("Par:Inits:domInit:personalStatementEdit", function(data) {
						new Par.PageContext.personalStatementEdit.init(data);
					});
					
					//Publish all Events for trigger-Elements on Page
					$$('[data-trigger]').each(function(el) {
						//Par.debug("Found Trigger on Page: " + $(el).readAttribute('data-trigger'), 'info');
						Par.Helper.publishEvent("Par:Inits:domInit:" + $(el).readAttribute('data-trigger'), {"onElement": el});
					});
				}

				
				Par.Helper.subscribeEvent("Par:PageContext:action:personalDataSaved", function(data) {
					new Par.PageContext.personalDataSaved(data);
				});
				Par.Helper.subscribeEvent("Par:PageContext:action:updateProfileCompletion", function() {
					new Par.PageContext.updateProfileCompletion();
				});
				
				
			} catch (e) {
				Par.debug("Error during Par:Inits:domInit: " + e, "error");
			}
			//Par.debug("All Events successfully set!", 'info');
		}

	},
	//********************************************************* /Inits **********************************************************
	//***************************************************************************************************************************

	//********************************************************* Debugging *******************************************************
	//***************************************************************************************************************************	
	/** @namespace Debug-Namspace for normal Logging and Error Logging 
	 * 
	 * @param {String|Number|DOMElement} str Object that should be written to Console
	 * @param {String} [logType] Optional: warn, error, plainLog
	 * */
	debug : function debug(str, logType) {
		if (typeof console === "undefined" || typeof console.debug === "undefined") {
			return false;
		}

		if (Par.Conf.get('isDevSystem') || Par.Conf.get('forceDebug')) {
			if(typeof logType === "undefined" ) {
				if (typeof str === "string" || typeof str === "number" || typeof console.dir === "undefined") {
					console.debug(Object.inspect(str));
				} else if (typeof str.stack !== "undefined") {
					console.error("CAUGHT EXCEPTION " + str.stack);
				} else {
					console.dir(str);
				}
			} else {
				if(logType == "warn") {
					console.warn(Object.inspect(str));
				} else if(logType == "error") {
					console.error(Object.inspect(str));
				} else if(logType == "plainLog") {
					console.debug(str);
				} else if(logType == "info") {
					console.info(str);
				}
			}
		}
	
	},

	Server : {
		log : function log() {
			//write something to server (db/fs) 
		},
	
		trackEvent : {
			omnEvents: {},
			add: function add(key, value) {
				this.omnEvents[key] = value;
				Par.debug("Added OMNEvent " + key);
			},
			get: function get(key) {
				return this.props[key];
			},
			exists: function exists(key) {
				return typeof this.props[key] !== 'undefined';
			}
		}
		
	},

	//********************************************************* /Debugging *******************************************************
	//***************************************************************************************************************************	
	
	//********************************************************* Helper **********************************************************
	//***************************************************************************************************************************
	/** @namespace Helper-Namspace for general Functions that can be used everywhere */
	Helper : {
		/**
		 * @class
		 * @description Publishes an Custom Event
		 * 				Events are published locally first if a DOM node is given, then bubble up as usual.
		 * 				If no DOM node is given, they are published only globally.
		 * 				<code>Par.Helper.publishEvent('Par:Inits:domInitReady', { });</code>
		 * @param {String} event_name event to publish, should be prefixed Par.
		 * @param {Object} memo optional payload to distribute to event subscribers. Local publishers should include the originating element as memo.source
		 * @param {DOMElement} node optional DOM node
		 */
		publishEvent: function publishEvent(event_name, memo, node) {
			var node = node || document;
			Par.debug("Published event *" + event_name + "* " + (node === document ? "globally" : "on node " + node), 'info');
			node.fire(event_name, memo);
		},
		
		/**
		 * @class
		 * @description Subscribes to an Event, can access data via e.memo
		 * 				Can subscribe globally, or locally on specific elements. Locally subscribed handlers 
		 * 				are allowed to stop further (global) event propagation.
		 * 				<code>Par.Helper.subscribeEvent('Par:form:afterSubmit:onError', function(e){ alert(e.memo) } }</code>
		 * 				<code>Par.Helper.subscribeEvent('Par:form:afterSubmit:onError', function(e){ alert(e.memo)}, $('element') }</code>
		 * @param {String} event_name event to subscribe to, should be prefixed Par.
		 * @param {Function} subscriber
		 * @param {DOMElement} node optional DOM node
		 */
		subscribeEvent: function subscribeToEvent(event_name, subscriber, node) {
			var node = node || document;
			Par.debug("Subscribed to event '" + event_name + "' " + (node === document ? "globally" : "on node " + node), 'info');
			node.observe(event_name, subscriber);
		},
		
		/**
		 * @class
		 * @description Laedt dynamisch die benoetigten Js-Dateien nach
		 * @param {Array} script Die Scripte, die eingebunden werden sollen
		 * @param {String} path optional path to script that should be loaded
		 */
		loadScript: function (script, path, callback) {
			if (!path) path = pageVars.jsPath;
			var obj = document.createElement('script');
			obj.setAttribute('type', 'text/javascript');
			obj.setAttribute('src', path + script + '.js');
			document.getElementsByTagName('head')[0].appendChild(obj);
			obj.onload = function() { 
			    if ( ! obj.onloadDone ) {
			    	obj.onloadDone = true; 
			    	callback(); 
			    }
			};
			/* IEs 
			 * domscript.onreadystatechange = function() { 
			    if ( ( "loaded" === domscript.readyState || "complete" === domscript.readyState ) && ! domscript.onloadDone ) {
			        domscript.onloadDone = true; 
			        init();
			    }
			}*/
		},


		/**
		 * @class
		 * @description Laedt dynamisch die benoetigten CSS-Dateien nach
		 * @param {Array} style Array mit den CSS-Dateinamen (ohne Suffix)
		 */
		loadCss: function (style) {
			var obj = document.createElement('link');
			obj.setAttribute('rel', 'stylesheet');
			obj.setAttribute('type', 'text/css');
			obj.setAttribute('media', 'screen, projection');
			obj.setAttribute('href', pageVars.cssPath + style + '.css');
			document.getElementsByTagName('head')[0].appendChild(obj);
		},
		
		/**
		 * @class
		 * @description Laedt dynamisch die benoetigten CSS-Dateien nach
		 * @param {Array} style Array mit den CSS-Dateinamen (ohne Suffix)
		 */
		trackAjaxPage: function (which) {
			PS.debug("Track Page: " + which);
			s.pageName = which;
			var s_code=s.t();if(s_code)document.write(s_code)
		},
		
		
		/**
		 * @class
		 * @description Lisents for onsubmit and prevents a double submit of a Form
		 **/
		preventDoubleSubmit: {
			/**
			 * @description Public Init Method
			 * @param {DOMElement} formEl Element that should be disabled
			 **/
			init: function init(message) {
				formEle = message.onElement;
				formEle.observe('submit', function(evt) {
					if(Par.Conf.exists('submitInProgress')) {
						Par.Helper.preventDoubleSubmit._stopEvent(evt);
					} else {
						Par.Conf.add('submitInProgress', true);
					}
				});
			},
			
			_stopEvent: function stopEvent(evt) {
				//alert(Par.Helper.preventDoubleSubmit.moeglichkeit1);
				evt.stop();
			}
		},
		
		
		
		/**
		 * @class
		 * @description Can make a Button appear disabled (but remains clickable actually)
		 **/
		buttonDisable: {
			/**
			 * @description Public Init Method
			 * @param {DOMElement} btnEle Element that should be disabled
			 * @param {DOMElement} clickEles Element(s) that should make the Button enabled again
			 **/
			init: function init(btnEle, clickEles) {
				this.btnEle = btnEle;
				var c = this;
				if (clickEles) {
					clickEles.each(function (e) {
						Event.observe(e, 'click', c._click.bindAsEventListener(c));
					});
				}
				this._disableBtn();
			},
			/** @lends Par.Helper.buttonDisable */
			_click: function click() {
				this._enableBtn();
			},
			_disableBtn: function disableBtn(evt) {
				evt.stop();
				this.btnEle.setOpacity(0.3);
				this.btnEle.setStyle({
					cursor: 'default'
				});
				this.btnEle.onclick = function () {
					return false;
				};
			},
			_enableBtn: function enableBtn() {
				this.btnEle.setOpacity(1);
				this.btnEle.setStyle({
					cursor: 'pointer'
				});
				this.btnEle.onclick = null;
			}
			
		}
		
	},
	
	PageContext : {
		
		/**
		 * @class
		 * @description on myProfile Pages after saving an AjaxForm the Completion has to be updated on Box on topright 
		 */
		updateProfileCompletion : Class.create(function () {
			return {
				initialize: function (url) {
					if (($('ps_myProfileStatusBox') || $$('.ps_profile_edit_page')[0]) && $$('.ps_statusBar')[0]) {
						if ($$('.profileUpdateUrl')[0] != null) {
							url = $$('.profileUpdateUrl')[0].value;
							new Ajax.Request(url, {
								method: 'get',
								onSuccess: function (response) {
									var myJson = response.responseText.evalJSON();
									if (Object.isUndefined(myJson.$errors) || Object.keys(myJson.$errors).length == 0) {
										if (myJson.profileCompletionValue) {
											if ($$('.ps_completionValueText')[0] != null) {
												$$('.ps_completionValueText')[0].update(myJson.profileCompletionValue + "%");
											}
											if ($('ps_completionValueBar')) {
												$('ps_completionValueBar').className = "ps_percentRemover upTo" + myJson.profileCompletionValue;
											}
										}
									}
		
								}
							});
						}
					}
				}
			};
		}()),
		
		
		/**
		 * @class
		 * @description General Class for openening, saving, closing ProfileElements (Factfile) on myProfile
		 */
		editFactfile : Class.create(function () {
			var opt = {};
			return {
				initialize: function (eventData) {
					this._options = Object.extend({}, opt);
					this._options = Object.extend(this._options, eventData.memo);
					this._openEditField = this.openEditField;
					this._cancelEditField = this.cancelEditField;
					this._editEntries = this.editEntries;
					myTransmissionInProgress = false;
				},
				/*
				 * Can be called by individual ProfileElement Functions to get the standard Set of Events set
				 * */
				initStandardButtons: function() { //Buttons that are present for all EditFields
					this._options.onElement.select('.ps_savedElementValue')[0].observe('click', this._openEditField.bindAsEventListener(this) );
					this._options.onElement.select('.ps_editIcon')[0].observe('click', this._openEditField.bindAsEventListener(this) );
					this._options.onElement.select('.ps_cancel')[0].observe('click', this._cancelEditField.bindAsEventListener(this) );
					this._options.onElement.select('.ps_cancelX')[0].observe('click', this._cancelEditField.bindAsEventListener(this) );
					//this._options.onElement.select('.ps_selectBoxItem')[0].observe('click', this._editEntries.bindAsEventListener(this) );
				},
				/*
				 * Successfull callback. Write JSONtext to DOM for the User
				 * */
				writeAsTextToDom: function(myJson) {
					this._options.onElement.select('.ps_savedElementValue p.ps_currentSelected')[0].innerHTML = myJson.resultView.displayText; 
				},
				openEditField: function() {
					$$('.ps_editForm').each(function(ele) {
						if(ele.select('.ps_serverError')[0]) ele.select('.ps_serverError')[0].remove();
						ele.select('.ps_viewElements')[0].removeClassName("ps_inv");
						ele.select('.ps_editFormElement')[0].addClassName("ps_inv");
						ele.select('.ps_errorValidation')[0].addClassName("ps_inv");
						ele.select('.ps_indicator')[0].addClassName("ps_inv");
						ele.select('.ps_viewHeadline')[0].addClassName("ps_inv");
						ele.select('.ps_savedElementValue')[0].removeClassName("ps_highlight");
						ele.select('.ps_cancelX')[0].addClassName("ps_inv");
					})
					
					$(this._options.onElement).select('.ps_cancelX')[0].removeClassName("ps_inv");					
					$(this._options.onElement).select('.ps_editIcon')[0].addClassName("ps_inv");
					$(this._options.onElement).select('.ps_viewHeadline')[0].removeClassName("ps_inv");
					$(this._options.onElement).select('.ps_savedElementValue')[0].addClassName("ps_highlight");
					//$(this._options.onElement).select('.ps_viewElements')[0].addClassName("ps_inv");
					$(this._options.onElement).select('.ps_editFormElement')[0].removeClassName("ps_inv");
					prevValue = $(this._options.onElement).select('.ps_savedElementValue p.ps_currentSelected')[0].innerHTML;
				},
				cancelEditField: function() {
					if($(this._options.onElement).select('.ps_serverError')[0]) $(this._options.onElement).select('.ps_serverError')[0].remove();
					$(this._options.onElement).select('.ps_viewElements')[0].removeClassName("ps_inv");
					$(this._options.onElement).select('.ps_editIcon')[0].removeClassName("ps_inv");
					$(this._options.onElement).select('.ps_cancelX')[0].addClassName("ps_inv");
					$(this._options.onElement).select('.ps_editFormElement')[0].addClassName("ps_inv");
					$(this._options.onElement).select('.ps_errorValidation')[0].addClassName("ps_inv");
					$(this._options.onElement).reset();
					$(this._options.onElement).select('.ps_indicator')[0].addClassName("ps_inv");
					$(this._options.onElement).select('.ps_viewHeadline')[0].addClassName("ps_inv");
					$(this._options.onElement).select('.ps_savedElementValue')[0].removeClassName("ps_highlight");
					$(this._options.onElement).select('.ps_savedElementValue p.ps_currentSelected')[0].innerHTML = prevValue;
					$(this._options.onElement).select('li').each(function(ele) {
						ele.removeClassName('ps_selectBoxItemActive');
						if(ele.innerHTML == prevValue) ele.addClassName("ps_selectBoxItemActive");
					});	
				},
				saveEditField: function(callback) {
					if($(this._options.onElement).select('.ps_serverError')[0]) $(this._options.onElement).select('.ps_serverError')[0].remove();
					$(this._options.onElement).select('.ps_indicator')[0].removeClassName("ps_inv");
					
					_url = $(this._options.onElement).action;
					//_url = "/intern/selenium/showstatictemplate?templatename=prototest";
					parameters = $(this._options.onElement).serialize(true);

					if(myTransmissionInProgress) {
						//PS.debug("transmissionInProgress");
					} else {
						myTransmissionInProgress = true;
						_onElement = this._options.onElement;

						new Ajax.Request(_url, {
							method: 'post',
							parameters: parameters,
							onSuccess: function (response) {
								myTransmissionInProgress = false;
								var myJson = response.responseText.evalJSON();
								if (myJson.resultView.success) { //Wie der Fehlerfall aussieht ist noch nicht definiert / mit AppDev klären
									$(_onElement).select('.ps_editFormElement')[0].addClassName("ps_inv");
									$(_onElement).select('.ps_viewElements')[0].removeClassName("ps_inv");
									$(_onElement).select('.ps_indicator')[0].addClassName("ps_inv");
									$(_onElement).select('.ps_viewHeadline')[0].addClassName("ps_inv");
									$(_onElement).select('.ps_savedElementValue')[0].removeClassName("ps_highlight");
									$(_onElement).select('.ps_cancelX')[0].addClassName("ps_inv");
									$(_onElement).select('.ps_editIcon')[0].removeClassName("ps_inv");
									callback(myJson);								
									if ((myJson.resultView.approvalStatus == "disapproved")) {
										$(_onElement).select('.ps_noApproval')[0].addClassName("ps_show");
									}
									if ((myJson.resultView.approvalStatus == "rejected")) {
										$(_onElement).select('.ps_rejected')[0].addClassName("ps_show");
									}
									Par.Helper.publishEvent("Par:PageContext:profile:elementSaved", { "savedElement": _onElement} );
								} else {
									if (myJson.errors.errorValidation) {
										//Hier soll dann der Fehler als übersetzter Text aus dem JSON kommen, der wird dann nur noch in das ErrorDiv geschrieben 
										$(_onElement).select('.ps_errorValidation')[0].removeClassName("ps_inv");
										$(_onElement).select('.ps_indicator')[0].addClassName("ps_inv");
									}
								}
		
							},
							onFailure: function() {
								//Eventuell Tracking für Fehler hier rein?
								myTransmissionInProgress = false;
								$(_onElement).select('.ps_indicator')[0].addClassName("ps_inv");
								var jsError = "<p class='ps_serverError'>Error 500</p>"; //only inserted by JS without translation
								$(_onElement).select('.ps_editFormElement')[0].insert({ bottom: jsError });
								PS.debug("AJAX form submission failed for: " + $(_onElement).id);
							}
							
						});
					

					}//transmission
					
				}
			};
		}()),
		
		/**
		 * @class
		 * @description Set Events and define Callback for MaritalStatus
		 * We want ot keep this as flexible as possible without too much code duplication
		 **/
		editMaritalStatus : {
			init: function init (data) {
				var myEditMethod = new Par.PageContext.editFactfile(data);
				myEditMethod.initStandardButtons();
				var savedValue = $$('#ps_viewMaritalStatus .ps_currentSelected')[0].innerHTML;
				$$('#ps_editMaritalStatus li').each(function(ele) {
					ele.observe('click', function() {
						$$('#ps_editMaritalStatus li').each(function(ele) {
							ele.removeClassName('ps_selectBoxItemActive');
						});						
						savedValue = ele.innerHTML;
						$('maritalStatus').value = ele.id;
						ele.addClassName("ps_selectBoxItemActive");
						myEditMethod.writeAsTextToDom({resultView:{displayText:savedValue}});
					})
					.observe('mouseover', function() {
						myEditMethod.writeAsTextToDom({resultView:{displayText:ele.innerHTML}});
					})
					.observe('mouseout', function() {
						myEditMethod.writeAsTextToDom({resultView:{displayText:savedValue}});
					});
				})				
				$(data.memo.onElement).select('.ps_save')[0].observe('click', function() {
					myEditMethod.saveEditField(function(myJson) {//callback function
						myEditMethod.writeAsTextToDom(myJson);
					});				
				});

			}
		},
		
		
		/**
		 * @class
		 * @description Set Events and define Callback for Smoker
		 **/
		editSmoker : {
			init: function init (data) {
				var myEditMethod = new Par.PageContext.editFactfile(data);
				myEditMethod.initStandardButtons();
				var savedValue = $$('#ps_viewSmoker .ps_currentSelected')[0].innerHTML;
				$$('#ps_editSmoker li').each(function(ele) {
					ele.observe('click', function() {
						$$('#ps_editSmoker li').each(function(ele) {
							ele.removeClassName('ps_selectBoxItemActive');
						});
						savedValue = ele.innerHTML;
						$('smoker').value = ele.id;
						ele.addClassName("ps_selectBoxItemActive");
						$$('#ps_viewSmoker .ps_currentSelected')[0].innerHTML = ele.innerHTML;
					});
					
					ele.observe('mouseover', function() {
						myEditMethod.writeAsTextToDom({resultView:{displayText:ele.innerHTML}});
					});
					ele.observe('mouseout', function() {
						myEditMethod.writeAsTextToDom({resultView:{displayText:savedValue}});
					});
				})		
				$(data.memo.onElement).select('.ps_save')[0].observe('click', function() {
					myEditMethod.saveEditField(function(myJson) {//callback function
						myEditMethod.writeAsTextToDom(myJson);
					});
				});
			}
			
		},
		
		/**
		 * @class
		 * @description Set Events and define Callback for BodyType
		 **/
		editBodyType : {
			init: function init (data) {
				var myEditMethod = new Par.PageContext.editFactfile(data);
				myEditMethod.initStandardButtons();
				var savedValue = $$('#ps_viewBodyType .ps_currentSelected')[0].innerHTML;
				$$('#ps_editBodyType li').each(function(ele) {
					ele.observe('click', function() {
						$$('#ps_editBodyType li').each(function(ele) {
							ele.removeClassName('ps_selectBoxItemActive');
						});
						savedValue = ele.innerHTML;
						$('bodyType').value = ele.id;
						ele.addClassName("ps_selectBoxItemActive");
						$$('#ps_viewBodyType .ps_currentSelected')[0].innerHTML = ele.innerHTML;
					});
					
					ele.observe('mouseover', function() {
						myEditMethod.writeAsTextToDom({resultView:{displayText:ele.innerHTML}});
					});
					ele.observe('mouseout', function() {
						myEditMethod.writeAsTextToDom({resultView:{displayText:savedValue}});
					});
				})		
				$(data.memo.onElement).select('.ps_save')[0].observe('click', function() {
					myEditMethod.saveEditField(function(myJson) {//callback function
						myEditMethod.writeAsTextToDom(myJson);
					});
				});
			}
			
		},
		editSport : {
			init: function init (data) {
				var myEditMethod = new Par.PageContext.editFactfile(data);
				myEditMethod.initStandardButtons();
			}
			
		},
		
		
		/**
		 * @class
		 * @description Für alle ProfilTabs, die per Ajax geladen werden sollen / wurden  
		 **/
		profileTabs : {
			init: function init (data) {
				if($('ps_aboutTab') != null) {
					$('ps_aboutTab').observe('click', function() {
						Par.PageContext.profileTabs.loadTab('about', data.onPage);
					});
				}
				if($('ps_interestsTab') != null) {
					$('ps_interestsTab').observe('click', function() {
						Par.PageContext.profileTabs.loadTab('interests', data.onPage);
					});
				}
				if($('ps_leisureTab') != null) {
					$('ps_leisureTab').observe('click', function() {
						Par.PageContext.profileTabs.loadTab('leisure', data.onPage);
					});
				}
				if($('ps_compatibilityTab') != null) {
					$('ps_compatibilityTab').observe('click', function() {
						Par.PageContext.profileTabs.loadTab('compatibility', data.onPage);
					});
				}
				if($('ps_1on1mailboxTab') != null && !$('ps_1on1mailboxTab').hasClassName('ps_tabDisabled')) { //if not disabled
					$('ps_1on1mailboxTab').observe('click', function() {
						Par.PageContext.profileTabs.loadTab('1on1mailbox', data.onPage);
					});
				}
				
				
				//Initiales laden des ersten Tabs
				if(!$('ps_aboutTabContent').hasClassName("ps_inv")) { //which tab is visible
					Par.PageContext.profileTabs.loadTab('about', data.onPage);	
				} else if(!$('ps_interestsTabContent').hasClassName("ps_inv")) {
					Par.PageContext.profileTabs.loadTab('interests', data.onPage);	
				} else if(!$('ps_leisureTabContent').hasClassName("ps_inv")) {
					Par.PageContext.profileTabs.loadTab('leisure', data.onPage);	
				} else if(!$('ps_compatibilityTabContent').hasClassName("ps_inv")) {
					Par.PageContext.profileTabs.loadTab('compatibility', data.onPage);	
				} else if(!$('ps_1on1mailboxTabContent').hasClassName("ps_inv")) {
					Par.PageContext.profileTabs.loadTab('1on1mailbox', data.onPage);	
				}
				Par.PageContext.profileTabs.prefetch(data);
			},
			
			/**
			 * @class
			 * @description If the Content is already in the DOM do not fetch it again via Ajax  
			 **/
			prefetch: function prefetch(data) {
				//Hier die Liste der Tabs durchgehen und mit den ids [x]TabAlreadyLoaded vergleichen und den jeweils nächsten Tab laden
				//Vielleicht aber erst einmal ein wenig mit Omniture messen und sehen, wieviele Leute die anderen Reiter überhaupt anklicken
				//Ansonsten laden wir unnötig viele Daten nach.
				prefetchAfterSeconds = 6 * 1000;
				_onPage = data.onPage;
				//window.setTimeout("Par.PageContext.profileTabs.loadTab('interests', _onPage, true, true)", prefetchAfterSeconds);
				window.setTimeout("if($('ps_aboutTabAlreadyLoaded') == null) { Par.PageContext.profileTabs.loadTab('about', _onPage, true, true)}",3000);
				window.setTimeout("if($('ps_leisureTabAlreadyLoaded') == null) { Par.PageContext.profileTabs.loadTab('leisure', _onPage, true, true)}", prefetchAfterSeconds);  //6 sec
				window.setTimeout("if($('ps_compatibilityTabAlreadyLoaded') == null) { Par.PageContext.profileTabs.loadTab('compatibility', _onPage, true, true)}", prefetchAfterSeconds * 3);//18 sec
			},
			
			hideAllTabs: function hideAllTabs() {
				$$('.ps_tabList li').each(function(tab) {
					tab.removeClassName("ps_active");
				})
				$$('.ps_tabContents').each(function(tabContent) {
					tabContent.addClassName("ps_inv");
				})
			},
			
			
			/**
			 * @class
			 * @description  Läd einzelne Tabs per Ajax (als Prefetch oder direkt mit Anzeige)
			 **/
			loadTab: function loadTab(which, onPage, justPrefetch, refresh) {
				if(!justPrefetch) {
					if($('ps_'+which+'Tab') != null) {
						Par.PageContext.profileTabs.hideAllTabs();
						$('ps_'+which+'Tab').addClassName("ps_active");
						$('ps_'+which+'TabContent').removeClassName("ps_inv");
					}
				}
				if(!refresh && $('ps_'+which+'TabAlreadyLoaded')) {
					PS.debug(which + " TabAlreadyLoaded");
					Par.PageContext.profileTabs.trackTabPages(which, onPage);
				} else {
					if($('ps_'+which+'TabContent') != null ) {//&& !$('ps_'+which+'TabAlreadyLoaded')
						_url = $('ps_'+which+'TabContent').readAttribute("data-url");
						myTransmissionInProgress = true;
						
						new Ajax.Request(_url, {
							method: 'get',
							onSuccess: function (response) {
								myTransmissionInProgress = false;
								$('ps_'+which+'TabContent').innerHTML = response.responseText;
								Par.Helper.publishEvent("Par:Inits:domInit:tabLoaded", { "loadedTab": which, "onPage":onPage, "refresh": refresh} );
							},
							onFailure: function() {
								myTransmissionInProgress = false;
								$$("#ps_"+which+"TabContent .ps_indicator")[0].addClassName("ps_inv");
								$$("#ps_"+which+"TabServerError")[0].removeClassName("ps_inv");
							}
						})
					} //Tabcontent != null

				}	
			},
			
			/**
			 * @class
			 * @description After the Snippet has been loaded we have to set some Events to the DOM  
			 * Ab hier unterscheidet sich die Logik für die einzelenen Seiten voneinander - Vorher ist für alle Tabs das gleich zu tun
			 **/
			initAjaxDom: function initAjaxDom(which) {
				loadedTab = which.memo.loadedTab;
				onPage = which.memo.onPage;
				refresh = which.memo.refresh;

				if(loadedTab == "about") {
					if(onPage == "myProfile") {
						Par.PageContext.editTabAboutMe.init();
					} else { //myProfile						
						//Par.PageContext.editTabInterest.init();
					}
				}
				if(loadedTab == "interests") {					
					//make Calls here for different Methods (one for each case partnerProfileInterests / myProfileInterests)??
					$$('#ps_interestsTabContent .ps_tooltip').each(function(tip) {
						new Helper.PS_tooltip(tip);
					})
					if(onPage == "partnerProfile") {
						Par.PageContext.editTabInterest.setZoomEvents();
					} else { //myProfile						
						Par.PageContext.editTabInterest.init();
					}
				}//interest
				if(loadedTab == "compatibility") {
					if(onPage == "partnerProfile") {
						$$('#ps_compatibilityTabContent .ps_tooltip').each(function(tip) {
							new Helper.PS_tooltip(tip);
						})
					}
				}
				if(loadedTab == "1on1mailbox") {
					if(onPage == "partnerProfile") {
						Par.PageContext.partnerMailbox.init();
					}
				}
				Par.PageContext.profileTabs.trackTabPages(loadedTab, onPage, refresh);
				
				//reportProfile Link
				new PageContext.PS_reportProfile(loadedTab);
			},
			
			/**
			 * @class
			 * @description Tracking for ProfileTabs  
			 * Soll nicht getrackt werden bei Preload, aber jedesmal, wenn der Tab gewechselt wird bei on click
			 **/
			trackTabPages: function trackTabPages(loadedTab, onPage, refresh) {
				//PS.debug(loadedTab +" - "+ onPage +" - "+ refresh);
				if(loadedTab == "about") {
					if(onPage == "partnerProfile") {
						if(!refresh) {
							Par.Helper.trackAjaxPage("partnerprofile_aboutme");
							Par.PageContext.profileTabs.pingTabVisited("aboutTab");
						}
					} else { //myProfile
						if(!refresh) Par.Helper.trackAjaxPage("myprofile_aboutme");
					}
				}
				if(loadedTab == "interests") {					
					if(onPage == "partnerProfile") {
						if(!refresh) {
							Par.Helper.trackAjaxPage("partnerprofile_interests");
							Par.PageContext.profileTabs.pingTabVisited("interestsTab");
						}
					} else { //myProfile						
						if(!refresh) Par.Helper.trackAjaxPage("myprofile_interests");
					}
				}
				if(loadedTab == "leisure") {					
					if(onPage == "partnerProfile") {
						if(!refresh) {
							Par.Helper.trackAjaxPage("partnerprofile_leisure");
							Par.PageContext.profileTabs.pingTabVisited("leisureTab");
						}
					} else { //myProfile						
						if(!refresh) Par.Helper.trackAjaxPage("myprofile_leisure");
					}
				}
				if(loadedTab == "compatibility") {					
					if(onPage == "partnerProfile") {
						if(!refresh) {
							Par.Helper.trackAjaxPage("partnerprofile_compatibility");
							Par.PageContext.profileTabs.pingTabVisited("compatibilityTab");
						}
					} else { //myProfile						
						if(!refresh) Par.Helper.trackAjaxPage("myprofile_compatibility");
					}
				}
				if(loadedTab == "1on1mailbox") {					
					if(onPage == "partnerProfile") {
						if(!refresh) {
							Par.Helper.trackAjaxPage("partnerprofile_1on1mailbox");
							Par.PageContext.profileTabs.pingTabVisited("1on1mailboxTab");
						}
					} else { //myProfile						
						if(!refresh) Par.Helper.trackAjaxPage("myprofile_1on1mailbox");
					}
				}
			},
			
			/**
			 * @class
			 * @description Calls a Controller for a Tab Visited (after second Tab clicked the mailOnNewVisitor will be triggered)
			 * Soll nicht getrackt werden bei Preload, aber jedesmal, wenn der Tab gewechselt wird bei on click
			 **/
			pingTabVisited: function(whichTab) {
				//URL aus dem DOM zusammenbasteln
				var _url = $("ps_" + whichTab + "Content").readAttribute('data-url');
				var _posi = _url.indexOf("?");
				//The Controller needs the listType-Parameter 
				var listPos =  window.location.href.indexOf("list=");
				if(listPos != -1) {
					var listType = "&list=" + window.location.href.substr(listPos+5, window.location.href.length);
				} else {
					var listType = "";
				}
				var _pingUrl = _url.substr(0, _posi) + "/visited" + _url.substr(_posi, _url.length) + listType;
				
				new Ajax.Request(_pingUrl, {
					method: 'get',
					onSuccess: function (response) {
						PS.debug("Par.PageContext.profileTabs.pingTabVisited: " + whichTab);
					},
					onFailure: function() {
						PS.debug("Failed: Par.PageContext.profileTabs.pingTabVisited: " + whichTab);
					}
				})
			}
			
		},
		
		
		/**
		 * @class
		 * @description Setzt alle Events und hat alle Funktionen für den Tab AboutMe auf der My-Seite (also Edit)  
		 **/
		editTabAboutMe : {
			init: function init () {
				myTransmissionInProgress = false;
				if($('ps_answerNewQuestion') != null) { //not all questions answered
					$('ps_answerNewQuestion').observe('click', function() {					
						Par.PageContext.editTabAboutMe.openNewQuestion();					
					});
					
					//in Modalbox
					$('ps_addMoreQuestions').observe('click', function() {
						Modalbox.hide(); //We have to hide the Box first. Otherwise Box will be opened twice and events get lost :/ 
						window.setTimeout("Par.PageContext.editTabAboutMe.openNewQuestion()", 300); //And we need this Timeout too...
					});
				} else {
					if($('ps_allQuestionsAnswered') != null) {//will be null if all questions answered
						if($('ps_addMoreQuestions')) $('ps_addMoreQuestions').addClassName("ps_inv");
						if($('ps_addMoreQuestions')) $$('.ps_orDo')[0].addClassName("ps_inv");
						
					}
				}
				
				if($$('.ps_question')[0] != null && $$('.ps_questionEdit')[0] != null) {
					Helper.saveAndEditQuestions.init();
					$$('#ps_aboutTabContent .ps_question').each(function(question) {
						question.select('.ps_answer')[0].observe('click', function() {
							Helper.saveAndEditQuestions.editQuestion(question, true, Par.PageContext.editTabAboutMe.editQuestion);
						})
						new Helper.updateTextareSize(question.select('textarea')[0]);
						question.select('.ps_questionCancel')[0].observe('click', Helper.saveAndEditQuestions.cancelQuestion.bindAsEventListener(this, question, Par.PageContext.editTabAboutMe.cancelEditQuestion));
						question.select('.ps_questionSave')[0].observe('click', Helper.saveAndEditQuestions.saveQuestion.bindAsEventListener(this, question, true, Par.PageContext.editTabAboutMe.saveEditQuestion));
						question.select('.ps_dragNDropper')[0].observe('mousedown', Par.PageContext.editTabAboutMe.toggleDragStyle.bindAsEventListener(this, question, true));
						question.select('.ps_dragNDropper')[0].observe('mouseup', Par.PageContext.editTabAboutMe.toggleDragStyle.bindAsEventListener(this, question, false));
					})
				}
				
				this.activateDragNDrop();
				
				$$('.ps_tabContents .ps_charLimit').each(function(charLimitEle) {
					new Helper.PS_inputObserver(charLimitEle);	
				})
				//Tooltips initialisieren
				$$('#ps_aboutMeList .ps_tooltip').each(function(tip) {
					new Helper.PS_tooltip(tip);
				})
				
			},
			
			editQuestion: function editQuestion() {
				Par.PageContext.editTabAboutMe.hideDragNDrop();
			},

			cancelEditQuestion: function cancelEditQuestion() {
				Par.PageContext.editTabAboutMe.activateDragNDrop();
			},

			saveEditQuestion: function saveEditQuestion() {
				Par.PageContext.editTabAboutMe.activateDragNDrop();
			},
			
			updateOrder:function updateOrder() {
				var order = Sortable.sequence($('ps_aboutMeList'));
				var element = "";
				$A(order).each(function(ele)  {
					element += "questionId=" + ele + "&";
				})
				var updateSortUrl = $('ps_aboutMeList').readAttribute("data-updateSortUrl")
				new Ajax.Request(updateSortUrl, {
					  method:'post',
					  parameters: element,
					  requestHeaders: {Accept: 'application/json'},
					  evalJS: false
				});
			},
			
			hideDragNDrop: function hideDragNDrop() {
				Sortable.destroy($('ps_aboutMeList'));
				$$('#ps_aboutMeList .ps_dragNDropper').each(function(dragger) {
					dragger.addClassName("ps_disabled");
					dragger.select(".ps_tooltip")[0].addClassName("ps_tooltipDisabled");
				})
				$$('#ps_aboutMeList .ps_question').each(function(quest) {
					quest.setStyle({'position':'static'})
				})
			},
			
			activateDragNDrop: function activateDragNDrop() {
				Sortable.create($('ps_aboutMeList'),{
					tag:'div',
					only:"ps_question",
					handle: "ps_dragNDropper",
					onUpdate: this.updateOrder.bind(this),
					scroll: window
				});
				$$('#ps_aboutMeList .ps_dragNDropper').each(function(dragger) {
					dragger.removeClassName("ps_disabled");
					dragger.select(".ps_tooltip")[0].removeClassName("ps_tooltipDisabled");
				})
				$$('#ps_aboutMeList .ps_question').each(function(quest) {
					quest.setStyle({'position':'relative'})
				})
			},
			
			toggleDragStyle: function activeDrag(ev, question, toggleOn) {
				if(toggleOn) {
					question.addClassName("ps_activeDrag");
				} else {
					question.removeClassName("ps_activeDrag");
				}
			},
			
			openNewQuestion: function openNewQuestion() {
				var _url = $('ps_answerNewQuestionForm').action;
				Modalbox.show(_url, {width: 580, skin: '1', hideCloseLink: false, confirmBeforeClosing: false, top:350, afterLoad:function() {
					if($('ps_questionSelect') != null) {
						Par.PageContext.editTabAboutMe.saveNewQuestion();
						$('ps_questionSelect').observe('change', function() {
							if($('ps_questionSelect').selectedIndex > 0) {
								allDisabledButtons.enableBtn();
							} else {
								allDisabledButtons.disableBtn();
							}
						});
						new Helper.PS_inputObserver($('ps_answerTextarea'));
					}
				}});
			},
			
			saveNewQuestion: function saveNewQuestion() {
				$('ps_answerSave').observe('click', function() {
					question = $('ps_newQuestion');
					_url = question.select('form')[0].action;
					if(myTransmissionInProgress) {
						//PS.debug("transmissionInProgress");
					} else {
						if($('ps_answerTextarea').value.length == 0 || $('ps_questionSelect').selectedIndex == 0) {
							question.select('.ps_indicator')[0].addClassName("ps_inv");
							if($('ps_answerTextarea').value.length == 0) {
								question.select('.ps_errorQuestion')[0].addClassName("ps_inv");
								question.select('.ps_errorEmpty')[0].removeClassName("ps_inv"); //please write answer
							} else if($('ps_questionSelect').selectedIndex == 0) {
								question.select('.ps_errorEmpty')[0].addClassName("ps_inv");
								question.select('.ps_errorQuestion')[0].removeClassName("ps_inv");//please select question
							}
							Modalbox.autoresizeHeight();
						} else {
							question.select('.ps_errorEmpty')[0].addClassName("ps_inv");
							question.select('.ps_errorQuestion')[0].addClassName("ps_inv");
							
							myTransmissionInProgress = true;
							$$('#ps_newQuestion .ps_indicator')[0].removeClassName("ps_inv");
							new Ajax.Request(_url, {
								method: 'post',
								parameters: {
									"questionId" : $(question).select('.questionId')[0].value,
									"answer": $(question).select('textarea')[0].value
								},
								onSuccess: function (response) {
									myTransmissionInProgress = false;
									result = response.responseText.evalJSON();
									if (result.resultView.success == true) {						
										Modalbox.show($('ps_modal_questionSuccess'), {width:400, skin:'1', confirmBeforeClosing: false, top:350});
										Par.PageContext.editTabAboutMe.refreshAboutList();
									}
								},
								onFailure: function() {
									myTransmissionInProgress = false;
									question.select('.ps_indicator')[0].addClassName("ps_inv");
									question.select('.ps_error500')[0].removeClassName("ps_inv");
									Modalbox.autoresizeHeight();
								}
							})
						}//length==0
					}//transmission
				})
			},
			
			refreshAboutList:function refreshAboutList() {
				Par.Helper.publishEvent("Par:PageContext:action:updateProfileCompletion", {});
				Par.PageContext.profileTabs.loadTab('about', "myProfile", false, true);
			}
			
		},
		
		/**
		 * @class
		 * @description Setzt alle Events und hat alle Funktionen für den Tab Interests auf der My-Seite (also Edit)  
		 **/
		editTabInterest : {
			init: function init () {
				
				$$('.ps_interest').each(function(interest) {
					interest.select('.ps_removeInterest')[0].observe('click', function() {

						interest_id = interest.id;
						subategory_id = interest.getElementsByClassName('SubCategoryID')[0].getValue();						
						Par.PageContext.editTabInterest.delete_interest(interest_id, subategory_id);
					});				
				})
				
				$$('.ps_addInterest').each(function(add_interest) { 
					add_interest.observe('click', function() {						
						subcategory_id = add_interest.getElementsByClassName('SubCategoryID')[0].getValue();
						subcategory_name =  add_interest.up(".ps_interestsSubcategory").select('.ps_subCategoryName')[0].innerHTML;
						interestPosition = add_interest.positionedOffset()[1]; //sprechender
												
						Par.PageContext.editTabInterest.add_interest_openModalBox(subcategory_id, interestPosition, subcategory_name);
					});					
				})				
				
				$('ps_addNewInterestSubmit').observe('click', function() {					
					Par.PageContext.editTabInterest.save_interest();					
				});	
				$('ps_addInterestsForm').observe('keypress', function(event) {
					 if(event.keyCode == Event.KEY_RETURN) {
						Par.PageContext.editTabInterest.save_interest();
						Event.stop(event);
					}
										
				});	
				
				Par.PageContext.editTabInterest.setZoomEvents();
				
			},
			
			setZoomEvents: function setZoomEvents() {
				// zum vergroessern
				$$('.ps_interest').each(function(interest) {
					interest.observe('mouseover', function() {					
						interest.select('.ps_interest_big')[0].removeClassName('ps_inv');
					});				
				})
				
				$$('.ps_interest').each(function(interest) {
					interest.observe('mouseout', function() {					
						interest.select('.ps_interest_big')[0].addClassName('ps_inv');
					});				
				})
			},
			
			/// xxx
			delete_interest: function delete_interest (interest_id, interest_subcategory_id) {
				_url = "/profile/deleteInterest"; //aus Template holen							
				myTransmissionInProgress = true;		
				new Ajax.Request(_url, {
					method: 'post',
					parameters: {
						"subcategory" : interest_subcategory_id,
						"interest": interest_id
					},
					onSuccess: function (response) {
						myTransmissionInProgress = false;
						$(interest_id).remove();
					},
					onFailure: function() {
						myTransmissionInProgress = false;
						alert("Error 500 !!!");
					}
				})				
				
			},
						
			//xxxx
			add_interest_openModalBox: function add_interest (interest_subcategory_id, interestPosition, subategory_name) {
				$('ps_editSubCategoryID').setValue(interest_subcategory_id);
				interestPosition = interestPosition + 100;
				$$('.ps_modal_addInterest_label')[0].innerHTML = subategory_name;
				$("ps_emptyNameError").addClassName('ps_inv');
				Modalbox.show($('ps_modal_addInterest'), {width: 460, skin: '1', confirmBeforeClosing: false, top: interestPosition });
			},
			
			
			save_interest: function save_interest () {				
				
				selectedSubcategory = $('ps_editSubCategoryID').getValue();
				newInterestName = $('ps_newInterestName').getValue();
												
				_url = "/profile/addInterest";
				myTransmissionInProgress = true;
				//kein Indicator?				
				new Ajax.Request(_url, {
					method: 'post',
					parameters: {
						"subcategory" : selectedSubcategory,
						"interestValue": newInterestName
					},
					onSuccess: function (response) {
						myTransmissionInProgress = false;						
						result = response.responseText.evalJSON();
		
						if (result.resultView.success == true) {						
							Par.PageContext.editTabInterest.showNewInterest(result);
						} else if(result.resultView.errorCode == "EMPTY") {
							$("ps_emptyNameError").removeClassName('ps_inv');
						} else {
							alert("Fehler: konnte kein Intresee hinzufuegen!!! ");
						}
												
					},
					onFailure: function() {
						myTransmissionInProgress = false;
						alert("Error 500 !!!");						
					}
				})				
				
				
			},
			
			//xxxx			
			showNewInterest: function showNewInterest(newInterestJSON){
				// Reset Modalbox
				$('ps_addInterestsForm').reset();
				Modalbox.hide($('ps_modal_addInterest'));
				 
				newInterestID = newInterestJSON.resultView.interestId;				 
				subcategoryID = newInterestJSON.resultView.subcategoryId;
				newInterestdisplayText = newInterestJSON.resultView.displayText;

				/* Create new Interests and fill with data */
				$$('#interestTemplate .SubCategoryID')[0].value = subcategoryID;
				$$('#interestTemplate .ps_interest')[0].setAttribute("id", newInterestID);
				tempId = Helper.getAntiCache();
				$$('#interestTemplate .ps_interest')[0].addClassName("ps_tempIDClass_" + tempId);
				$$('#interestTemplate .ps_interestImage').each(function(interestImg) {
					interestImg.setAttribute("src", "/static/redesign09/img/profile_interests/1.png");
				})
				
				$$('#interestTemplate .ps_interest_big .ps_interestName')[0].innerHTML = newInterestdisplayText;
				
				//shorten
				if(newInterestdisplayText.length > 13) {
					newInterestdisplayText = newInterestdisplayText.substr(0, 13) + "...";
				}
				
				$$('#interestTemplate .ps_interestName')[0].innerHTML = newInterestdisplayText;
				newInterestHTML = $('interestTemplate').innerHTML;
						
				// das neue Interesse nun in dem DOM haengen
				Element.insert($$('#ps_subcategory_' + subcategoryID + " .ps_addInterest")[0], {'before': newInterestHTML});
				
				$$('.ps_tempIDClass_'+tempId+' .ps_removeInterest')[0].observe('click', function(interest) {
					interest_id = newInterestID;
					subcategory_id = $$('.ps_tempIDClass_'+tempId +' .SubCategoryID')[0].value;
					Par.PageContext.editTabInterest.delete_interest(interest_id, subcategory_id);
				});
				// damit das zommen auch auf dem neuem Interesse klappt
				Par.PageContext.editTabInterest.setZoomEvents();
			}
			
			
		},
		
		
		/**
		 * @class
		 * @description In der partnerMail (1on1mailbox) muss der Pager per Ajax blaettern  
		 **/
		partnerMailbox : {
			init: function init () {
				if($$('#ps_1on1mailboxTabContent .ps_navFlip')[0] != null) {
					$$('#ps_1on1mailboxTabContent .ps_navFlip a').each(function(navLink) {
						navLink.observe("click", function(ev) {
							Event.stop(ev);
							
							var baseUrl = $('ps_1on1mailboxTabContent').readAttribute("data-url");
							var pageParam = navLink.href.toQueryParams();
							var callUrl = baseUrl + "&page=" + pageParam.page;
							
							new Ajax.Updater('ps_1on1mailboxTabContent', callUrl, {
								method: 'get',
								onComplete: function() {
									Par.PageContext.partnerMailbox.init();
								}
							});
							
						})
					})
				}
				
				//Tooltips initialisieren
				$$('#ps_1on1mailboxTabContent .ps_tooltip').each(function(tip) {
					new Helper.PS_tooltip(tip);
				})
				
			}
		},
		
		
		/**
		 * @class
		 * @description Oeffnet das Modal Window fuer die zipMap auf der Partner Profilseite  
		 **/
		zipMap : {
			init: function init () {
				$('ps_openZipMap').observe('click', function(event) {
					Event.stop(event);
					Modalbox.show(this.href, {width: 490, skin: '1', hideCloseLink: false, confirmBeforeClosing: false, afterLoad:function() {
						window.setTimeout("Modalbox.resizeModalBoxToContent()", 200);
					}});
					
				});	
				
			}
		},
		
		/**
		 * @class
		 * @description Makeing notes on partnerProfile
		 **/
		partnerNoteForm : {
			init: function init () {
				noteTextarea = $$("#ps_partnerNote textarea")[0];
				myUpdaterTextarea = new Helper.updateTextareSize(noteTextarea);
				$('ps_partnerNoteForm').observe('click', function(event) {
					$('ps_partnerNote').addClassName("ps_editMode");
				});
				$('ps_partnerNoteSave').observe('click', function(event) {
					Event.stop(event);
					Par.PageContext.partnerNoteForm.saveNote();
				});	
				$('ps_partnerNoteCancel').observe('click', function(event) {
					Event.stop(event);
					$('ps_partnerNoteForm').reset();
					$('ps_partnerNoteTextarea').focus();
					$('ps_partnerNoteTextarea').blur();
					$('ps_partnerNote').removeClassName("ps_editMode");
					$('ps_partnerNoteError500').addClassName("ps_inv");
				});	
			},
			
			saveNote: function() {
				_url = $('ps_partnerNoteForm').action;
				$$('#ps_partnerNoteForm .ps_indicator')[0].removeClassName("ps_inv");
				if(typeof allInputDefaults != "undefined") allInputDefaults.clearDefaultValuesBeforeSubmit("ps_partnerNoteForm");
				new Ajax.Request(_url, {
					method: 'post',
					parameters: {
						"loggedInUserId" : $F('ps_note_loggedInUserId'),
						"matchUserId" : $F('ps_note_matchUserId'),
						"note" : $F('ps_partnerNoteTextarea')
					},
					onSuccess: function (response) {
						$$('#ps_partnerNoteForm .ps_indicator')[0].addClassName("ps_inv");
						$('ps_partnerNote').removeClassName("ps_editMode");
						$('ps_partnerNoteError500').addClassName("ps_inv");
						$('ps_partnerNoteTextarea').defaultValue = $F('ps_partnerNoteTextarea');
						if(!Object.isUndefined(allInputDefaults)) allInputDefaults.fillDefaultValuesAfterSubmit("ps_partnerNoteForm");
					},
					onFailure: function() {
						$$('#ps_partnerNoteForm .ps_indicator')[0].addClassName("ps_inv");
						$('ps_partnerNoteError500').removeClassName("ps_inv");
					}
				})	
				
			}
		},
		
		
		/**
		 * @class
		 * @description Nice view StatusUpdate with Animation Candy and stuff
		 **/
		viewStatusUpdate : {
			init: function init (data) {
				var statusUpdate = data.memo.onElement;
				Par.PageContext.viewStatusUpdate.startAnimation();
				
				$(statusUpdate).select('#ps_sendCommentOnStatusUpdate')[0].observe('click', function(ev) {
					Event.stop(ev);
					Modalbox.show($(statusUpdate).select('#ps_sendCommentOnStatusUpdate')[0].href, {width:560, skin:'1'});
				})
				
				
			},
			
			startAnimation: function() {
				window.setTimeout("$('ps_statusBubbles').addClassName('ps_bubble1')", 400);
				window.setTimeout("$('ps_statusBubbles').addClassName('ps_bubble2')", 500);
				window.setTimeout("$('ps_statusBubbles').addClassName('ps_bubble3')", 600);
				window.setTimeout("$('ps_statusUpdateBox').removeClassName('ps_aniHide')", 650);
			}
		},
		
		/**
		 * @class
		 * @description Modallayer for ImageRelease on PartnerProfile
		 **/
		imageReleaseModal : {
			init: function init () {
				$('send_imagerelease').observe('click', function(event) {
					Modalbox.show($('send_imagerelease').readAttribute('data-modalurl'), {width: 500, skin: '1', afterLoad:function() {
						Par.PageContext.imageReleaseModal.initModal();
						Modalbox.autoresizeHeight();
					}});
				});
			},
			
			initModal: function() {
				if($('ps_releaseImageButton')) {
					$('ps_releaseImageButton').observe('click', function(event) {
						Par.PageContext.imageReleaseModal.sendImageRelease();
					})
					//Par.Helper.trackAjaxPage("partnerprofile_releaseImages");
				} else if($('ps_revokeImageButton')) {
					$('ps_revokeImageButton').observe('click', function(event) {
						Par.PageContext.imageReleaseModal.revokeImageRelease();
					})
					//Par.Helper.trackAjaxPage("partnerprofile_unreleaseImages");
				}
			},
			
			sendImageRelease: function() {
				releaseContainer = $$('.ps_imageReleaseContainer')[0];
				_url = $('ps_releaseForm').action;
				_message = "";
				if($('ps_releaseTextarea')) _message = $F('ps_releaseTextarea');
				releaseContainer.select('.ps_indicator')[0].removeClassName("ps_inv");

				new Ajax.Request(_url, {
					method: 'post',
					parameters: {
						"partnerId" : $F('releasePartnerUserId'),
						"body" : _message
					},
					onSuccess: function (response) {
						var myJson = response.responseText.evalJSON();
					
						releaseContainer.select('.ps_indicator')[0].addClassName("ps_inv");
						if(myJson.resultView.success) {
							Modalbox.show($('ps_modal_releaseSuccess'), {width:400, skin:'1'});
							new PageContext.PS_messagingPageUpdate();
							Par.Helper.publishEvent("ps:imageRelease:released", {}); //will trigger tracking comm_fotorelease							
						} else if(myJson.resultView.blockedFreeshot) {

							releaseContainer.select('#ps_blockedFreeshot')[0].removeClassName("ps_inv");
							Modalbox.autoresizeHeight();
						}
					},
					onFailure: function() {
						releaseContainer.select('.ps_indicator')[0].addClassName("ps_inv");
						if($('ps_blockedFreeshot')) {releaseContainer.select('#ps_blockedFreeshot')[0].addClassName("ps_inv");}
						releaseContainer.select('.ps_error500')[0].removeClassName("ps_inv");
					}
				})	
				
			},
			
			revokeImageRelease: function() {
				releaseContainer = $$('.ps_imageReleaseContainer')[0];
				_url = $('ps_revokeForm').action;
				releaseContainer.select('.ps_indicator')[0].removeClassName("ps_inv");
				new Ajax.Request(_url, {
					method: 'post',
					parameters: {
						"partnerId" : $F('revokePartnerUserId')
					},
					onSuccess: function (response) {
						new PageContext.PS_messagingPageUpdate();
						Modalbox.hide();
					},
					onFailure: function() {
						releaseContainer.select('.ps_indicator')[0].addClassName("ps_inv");
						releaseContainer.select('.ps_error500')[0].removeClassName("ps_inv");
					}
				})	
				
			}
			
		},
		

		/**
		 * @class
		 * @description Give or change Alias for Partner on PartnerProfile
		 **/
		partnerAlias : {
			init: function init () {
				$('ps_addAlias').observe('click', function(event) {
					Event.stop(event);
					Par.PageContext.partnerAlias.openAliasModal(this);
					
				});
				$('ps_changeAlias').observe('click', function(event) {
					Event.stop(event);
					Par.PageContext.partnerAlias.openAliasModal(this);
					
				});	
				
			},
			
			openAliasModal: function openAliasModal(ele) {
				Modalbox.show(ele.href, {width: 340, skin: '1', afterLoad:function() {
					//Modalbox.resizeModalBoxToContent();
					$$('#ps_aliasForm .ps_charLimit').each(function(charLimitEle) {
						new Helper.PS_inputObserver(charLimitEle);	
					});
					$('ps_saveAlias').observe('click', function(event) {
						Par.PageContext.partnerAlias.saveAlias();
					});	
					$('ps_aliasForm').observe('submit', function(event) {
						Event.stop(event);
						Par.PageContext.partnerAlias.saveAlias();
					});
				}});
			},
			
			saveAlias: function saveAlias() {
				var _url = $('ps_aliasForm').action;
				new Ajax.Request(_url, {
					method: 'post',
					parameters: $('ps_aliasForm').serialize(),
					onSuccess: function (response) {
						var myJson = response.responseText.evalJSON();
						if(myJson.alias.alias == "") { //removed Alias
							$('ps_aliasNameWrapper').addClassName("ps_inv");
							$('ps_aliasIdWrapper').removeClassName("ps_inv");
						} else {
							$('ps_partnerGivenAlias').innerHTML = myJson.alias.alias;
							$('ps_aliasNameWrapper').removeClassName("ps_inv");
							$('ps_aliasIdWrapper').addClassName("ps_inv");
						}
						Modalbox.hide();
					},
					onFailure: function() {
						releaseContainer.select('.ps_indicator')[0].addClassName("ps_inv");
						releaseContainer.select('.ps_error500')[0].removeClassName("ps_inv");
					}
				})	
			}
		},
		
		
		/**
		 * @class
		 * @description changeFavorite on PartnerProfile
		 **/
		editFavorite : {
			init: function init () {
				$$('.ps_addFavButton')[0].observe('click', function(event) {
					Event.stop(event);
					Par.PageContext.editFavorite.toggle(this);
				});
				$$('.ps_removeFavButton')[0].observe('click', function(event) {
					Event.stop(event);
					Par.PageContext.editFavorite.toggle(this);
				});	
				
			},
			
			toggle: function saveAlias(button) {
				var _url = button.href;
				new Ajax.Request(_url, {
					method: 'get',
					onSuccess: function (response) {
						var myJson = response.responseText.evalJSON();
						if(myJson.success == true) {
							if(button.hasClassName("ps_addFavButton")) {
								$$('.ps_addFavButton')[0].addClassName("ps_inv");
								$$('.ps_removeFavButton')[0].removeClassName("ps_inv");	
							} else {
								$$('.ps_addFavButton')[0].removeClassName("ps_inv");
								$$('.ps_removeFavButton')[0].addClassName("ps_inv");
							}
							
						} else {
							
						}
					}
				})	
			}
		},
		

		/**
		 * @class
		 * @description Click on MatchinGraphic on partnerProfilePage
		 **/
		matchingResultGraphic : {
			init: function init () {
				$$('.ps_matching_visual')[0].observe('click', function(event) {
					Par.PageContext.profileTabs.loadTab('compatibility', 'partnerProfile');
					new Helper.PS_scrollTo($('ps_profileTabArea'), 20);
				});
				
				originalSrc = $$('.ps_persons img')[0].src;
				darkendSrc = Helper.manipulateImageColor($$('.ps_persons img')[0].src, 10);
				
				$$('.ps_matching_visual')[0].observe('mouseover', function(event) {
					$$('.ps_persons img')[0].src = darkendSrc
				})
				$$('.ps_matching_visual')[0].observe('mouseout', function(event) {
					$$('.ps_persons img')[0].src = originalSrc
				})
				
			} 
			
		},
		

		/**
		 * @class
		 * @description Display notice layer on personaldata and profileprefill page on mouseover
		 **/
		showNotice: {
			init: function init () {
				var focusElement = "";
				$$('.ps_questionWithNotice').each(function(question) {
					//Handle Focus on Formelements in Questions
					elementArray = new Array("input", "select", "textarea");
					elementArray.each(function(formElement) {
						question.select(formElement).each(function(questFormElement) {//Suche in der Question ein FormElement
							questFormElement.observe('focus', function() {					
								focusElement = question;
								question.select('.ps_noticeBox')[0].removeClassName('ps_inv');			
							});	
							questFormElement.observe('blur', function() {
								focusElement = "";
								question.select('.ps_noticeBox')[0].addClassName('ps_inv');
							});
						})	
					})
					
					//Handle MouseOver
					question.observe('mouseover', function() {					
						question.select('.ps_noticeBox')[0].removeClassName('ps_inv');			
					});
					question.observe('mouseout', function() {
						if(question != focusElement) {
							question.select('.ps_noticeBox')[0].addClassName('ps_inv');
						}
					});
				})				
				
			}
		},
		
		/**
		 * @class
		 * @description Change select boxeson personaldata and profileprefill pages
		 **/
		toggleSelectbox: {
			init: function init () {
				$$('.ps_questionSelect').each(function(question) {
					Par.PageContext.toggleSelectbox.changeDisplay(question);
					question.observe('click', function() {						
						Par.PageContext.toggleSelectbox.changeDisplay(question);
					});
				})
			},
			
			changeDisplay: function changeDisplay (question) {
				if(question.value == "-1" || question.value == "null"){
					question.addClassName('ps_default');
				} else {
					question.removeClassName('ps_default');
				}
			}
		},
		
		
		/**
		 * @class
		 * @description Das personalStatement soll ein/ausklappen können, wenn mehrere Zeilen eingegeben wurden. 
		 **/
		personalStatementView: {
			init: function init () {
				if($$("#ps_viewPersonalStatement p")[0].getHeight() > 55) {
					$('ps_viewPersonalStatement').addClassName("ps_evenLonger");
					$('ps_viewPersonalStatement').observe('click', function() {						
						Par.PageContext.personalStatementView.toggleDisplayHeight();
					});
					
				}
			},
			
			toggleDisplayHeight: function displayAll() {
				if($('ps_viewPersonalStatement').hasClassName("ps_evenLonger")) {
					$('ps_viewPersonalStatement').addClassName("ps_displayAll");
					$('ps_viewPersonalStatement').removeClassName("ps_evenLonger");	
				} else {
					$('ps_viewPersonalStatement').removeClassName("ps_displayAll");
					$('ps_viewPersonalStatement').addClassName("ps_evenLonger");
				}
				
			}
		},

		/**
		 * @class
		 * @description Das personalStatement bearbeiten 
		 **/
		personalStatementEdit: {
			init: function init () {
				if($$('.ps_question')[0] != null && $$('.ps_questionEdit')[0] != null) {
					Helper.saveAndEditQuestions.init();
					$$('#ps_editPersonalStatement .ps_question').each(function(question) {
						question.select('.ps_answer')[0].observe('click', function() {
							Helper.saveAndEditQuestions.editQuestion(question, true);
						})
						new Helper.updateTextareSize(question.select('textarea')[0]);
						question.select('.ps_questionCancel')[0].observe('click', Helper.saveAndEditQuestions.cancelQuestion.bindAsEventListener(this, question));
						question.select('.ps_questionSave')[0].observe('click', Helper.saveAndEditQuestions.saveQuestion.bindAsEventListener(this, question, true, Par.PageContext.personalStatementEdit.saveCallback));
					})
				}
			},
			
			saveCallback: function saveCallback() {
				if($('ps_questionEdit_personalStat').value == "") {
					$('ps_editPersonalStatement').addClassName("ps_emptyStatement");
				} else {
					$('ps_editPersonalStatement').removeClassName("ps_emptyStatement");
				}
			}
			
		}
		
	}
};
	//********************************************************* /PageContext******************************************************
	//***************************************************************************************************************************
	
	Par.PageContext = Par.PageContext || {};
	
	Par.PageContext.secureLogin = Class.create(function () {
		var opt = {
				wrapper: "ul.loggedout",
				random: true,
				delay: 5,
				parameters: {
					op: "get_stories"
				}
		};
		
		function _doStuff(what) {
			//alert("i do stuff " + what + " - " + opt.wrapper);
		};
		
		return {
			initialize: function (eventData) {
				this._options = Object.extend({}, opt);
				this._options = Object.extend(this._options, eventData);
				//alert(eventData.memo.onElement.id);
				//alert(eventData.eventName);
				//alert("login do stuff " + this._options.random +" - "+ this._options.eventName);
				this.doYadda("intern");
				_doStuff("intern");
			},
			doYadda: function(what) {
				//alert("Yadda " + this._options.eventName);
				//alert("Yadda " + what);
			}
		};
	}());
	
	/**
	 * @class
	 * @description Called when the personalDateForm /settings/personadata is been saved to update all HTML with newest Data.
	 **/
	Par.PageContext.personalDataSaved = Class.create(function () {    
		var opt = {
			zipInForm: $('ps_form_element_display_zip'),
			cityInForm: $('ps_form_element_display_city'),
			zipAndCityOnProfileHead: $$('.ps_zipAndCity')[0]
		};
		return {
	        initialize: function (eventData) {
	        	this._options = Object.extend({}, opt);
	        	// When no error occured check if we have a profileCompletion Box on
				// page. If so do a Ajax-refresh on that Box
				if ($$('.ps_profile_edit_page')[0] && $$('.ps_statusBar')[0]) {
					Par.Helper.publishEvent("Par:PageContext:action:updateProfileCompletion", {});
				}
				if(this._options.zipInForm != null && this._options.cityInForm != null && this._options.zipAndCityOnProfileHead != null) {
					zipInForm = this._options.zipInForm.innerHTML.substr(0,2);
					this._options.zipAndCityOnProfileHead.update(this._options.cityInForm.innerHTML + " (" + zipInForm + "...)");
				}
	        	
	        }
	    };
	}());
	
	
	//********************************************************* /PageContext ****************************************************
	//***************************************************************************************************************************

		/**
		 * @class
		 * @description The Root of all Javascript Actions (All DOMEvents, Configuration and everything else starts here!
		 * @description Will be called immediately due to "()" 
		 */
		new function() {
			document.observe("dom:loaded", function () {
				"use strict";
				if (typeof(ps_js_timings) == "undefined") {
					ps_js_timings = {};
				}
				ps_js_timings.parshipJsFirstDomLoaded = new Date().getTime();
				PS = new PS_core();
				PSDom = new PS_dom();
				ps_js_timings.parshipJsFinished = new Date().getTime();
				Par.Inits.confInit();
				Par.Inits.domInit();				
				Par.Helper.publishEvent('Par:Inits:domInitReady', { });
				//Par.debug("debug-test");
				//Par.debug("warn-test", 'warn');
				//Par.debug("error-test", 'error');
				
				Par.debug("---------------------L-O-A-D-E-D (2.0)------------------------");
			});
		}();


