// constant char code for marking example values in text fields
var EXAMPLE_TEXT_MARKER = 183;

/* change input-field onFocus: remove default-text (ending with character 183), empty password-fields, change color*/
function init_inputOnFocusColorValues(){	

	$('input:text').focus(function(){
		//delete preinserted value in input field if value is marked with middledot (int value = 183)
		//otherwise leave value in the field
		tmp = this.value;
		if(tmp.charCodeAt(tmp.length-1)==EXAMPLE_TEXT_MARKER){
			this.value="";
		}
		if (this.className.indexOf("ep_input_color") == -1){
			this.className = this.className + " ep_input_color";
		}
	});
	
	$('input:password').focus(function(){
		this.value="";
		if (this.className.indexOf("ep_input_password_color") == -1){
			this.className = this.className + " ep_input_password_color";
		}
	});
	
	$('textarea').focus(function(){
		//delete preinserted value in input field if value is marked with middledot (int value = 183)
		//otherwise leave value in the field
		tmp = this.value;
		if(tmp.charCodeAt(tmp.length-1)==EXAMPLE_TEXT_MARKER){
			this.value="";
		}
		if (this.className.indexOf("ep_textarea_color") == -1){
			this.className = this.className + " ep_textarea_color";
		}
	});
	
	$(document).ready(function(){/*tooltip js not yet loaded*/
		$('.ep_custom_tooltip').tooltip({
					track: true, 
				    delay: 0, 
				    showURL: false, 
				    opacity: 1, 
				    fixPNG: true, 
				    top: 10, 
	    			left:10, 
				    extraClass: "ep_sp_tooltip ep_text_left"			    
		});
	});
}

// change textcolor for input fields which have an non-example entry 
function changeInputTextColor(){
	//change input fields
	var inputs = $('input:text');
	
	for (i=0; i<inputs.length; i++) {
		if(inputs[i].value.charCodeAt(inputs[i].value.length-1)!=EXAMPLE_TEXT_MARKER){
			if (inputs[i].className.indexOf("ep_input_color") == -1){
				inputs[i].className = inputs[i].className + " ep_input_color";
			}
		}
	}
	
	//change textareas
	var textareas =$('textarea');
	
	for (i=0; i<textareas.length; i++) {
		if(textareas[i].value.charCodeAt(textareas[i].value.length-1)!=EXAMPLE_TEXT_MARKER){
			if (textareas[i].className .indexOf("ep_textarea_color") == -1){
				textareas[i].className  = textareas[i].className  + " ep_textarea_color";
			}
		}
	}	
}

// hide additional data on loading page in basic data of a member
function hideAdditionalData(){
	if($('#ep_income_error').length > 0){
		$('#additionalData').show();
		$('#additionalDataLink').html('Zusatzdaten ausblenden');
	}else{
		$('#additionalData').hide();
	}	
}

/* calls of the defined methods */
if (jsAtTheBottom){	/* execute without delay */
	init_inputOnFocusColorValues();
	changeInputTextColor();	
	hideAdditionalData();
}else{
	$(document).ready(function(){
		init_inputOnFocusColorValues();
		changeInputTextColor();	
		hideAdditionalData();
	});
}
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4259 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '1.2'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		var val = this.is(':visible') ? 
				this[0]['offset' + name] : 
				num( this, name.toLowerCase() )
					+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
					+ num(this, 'padding' + torl) + num(this, 'padding' + borr);
		
		return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};

})(jQuery);
/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip-1.3.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
	
		// the tooltip element
	var helper = {},
		// the current tooltipped element
		current,
		// the title of the current element, used for restoring
		title,
		// timeout id for delayed tooltips
		tID,
		// IE 5.5 or 6
		IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		// flag for mouse tracking
		track = false;
	
	$.tooltip = {
		blocked: false,
		defaults: {
			delay: 200,
			fade: false,
			showURL: true,
			extraClass: "",
			top: 15,
			left: 15,
			id: "tooltip"
		},
		block: function() {
			$.tooltip.blocked = !$.tooltip.blocked;
		}
	};
	
	$.fn.extend({
		tooltip: function(settings) {
			settings = $.extend({}, $.tooltip.defaults, settings);
			createHelper(settings);
			return this.each(function() {
					$.data(this, "tooltip", settings);
					this.tOpacity = helper.parent.css("opacity");
					// copy tooltip into its own expando and remove the title
					this.tooltipText = this.title;
					$(this).removeAttr("title");
					// also remove alt attribute to prevent default tooltip in IE
					this.alt = "";
				})
				.mouseover(save)
				.mouseout(hide)
				.click(hide);
		},
		fixPNG: IE ? function() {
			return this.each(function () {
				var image = $(this).css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
					image = RegExp.$1;
					$(this).css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
					}).each(function () {
						var position = $(this).css('position');
						if (position != 'absolute' && position != 'relative')
							$(this).css('position', 'relative');
					});
				}
			});
		} : function() { return this; },
		unfixPNG: IE ? function() {
			return this.each(function () {
				$(this).css({'filter': '', backgroundImage: ''});
			});
		} : function() { return this; },
		hideWhenEmpty: function() {
			return this.each(function() {
				$(this)[ $(this).html() ? "show" : "hide" ]();
			});
		},
		url: function() {
			return this.attr('href') || this.attr('src');
		}
	});
	
	function createHelper(settings) {
		// there can be only one tooltip helper
		if( helper.parent )
			return;
		// create the helper, h3 for title, div for url
		helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
			// add to document
			.appendTo(document.body)
			// hide it at first
			.hide();
			
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			helper.parent.bgiframe();
		
		// save references to title and url elements
		helper.title = $('h3', helper.parent);
		helper.body = $('div.body', helper.parent);
		helper.url = $('div.url', helper.parent);
	}
	
	function settings(element) {
		return $.data(element, "tooltip");
	}
	
	// main event handler to start showing tooltips
	function handle(event) {
		// show helper, either with timeout or on instant
		if( settings(this).delay )
			tID = setTimeout(show, settings(this).delay);
		else
			show();
		
		// if selected, update the helper position when the mouse moves
		track = !!settings(this).track;
		$(document.body).bind('mousemove', update);
			
		// update at least once
		update(event);
	}
	
	// save elements title before the tooltip is displayed
	function save() {
		// if this is the current source, or it has no title (occurs with click event), stop
		if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
			return;

		// save current
		current = this;
		title = this.tooltipText;
		
		if ( settings(this).bodyHandler ) {
			helper.title.hide();
			var bodyContent = settings(this).bodyHandler.call(this);
			if (bodyContent.nodeType || bodyContent.jquery) {
				helper.body.empty().append(bodyContent)
			} else {
				helper.body.html( bodyContent );
			}
			helper.body.show();
		} else if ( settings(this).showBody ) {
			var parts = title.split(settings(this).showBody);
			helper.title.html(parts.shift()).show();
			helper.body.empty();
			for(var i = 0, part; (part = parts[i]); i++) {
				if(i > 0)
					helper.body.append("<br/>");
				helper.body.append(part);
			}
			helper.body.hideWhenEmpty();
		} else {
			helper.title.html(title).show();
			helper.body.hide();
		}
		
		// if element has href or src, add and show it, otherwise hide it
		if( settings(this).showURL && $(this).url() )
			helper.url.html( $(this).url().replace('http://', '') ).show();
		else 
			helper.url.hide();
		
		// add an optional class for this tip
		helper.parent.addClass(settings(this).extraClass);

		// fix PNG background for IE
		if (settings(this).fixPNG )
			helper.parent.fixPNG();
			
		handle.apply(this, arguments);
	}
	
	// delete timeout and show helper
	function show() {
		tID = null;
		if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
			if (helper.parent.is(":animated"))
				helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
			else
				helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
		} else {
			helper.parent.show();
		}
		update();
	}
	
	/**
	 * callback for mousemove
	 * updates the helper position
	 * removes itself when no current element
	 */
	function update(event)	{
		if($.tooltip.blocked)
			return;
		
		if (event && event.target.tagName == "OPTION") {
			return;
		}
		
		// stop updating when tracking is disabled and the tooltip is visible
		if ( !track && helper.parent.is(":visible")) {
			$(document.body).unbind('mousemove', update)
		}
		
		// if no current element is available, remove this listener
		if( current == null ) {
			$(document.body).unbind('mousemove', update);
			return;	
		}
		
		// remove position helper classes
		helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
		
		var left = helper.parent[0].offsetLeft;
		var top = helper.parent[0].offsetTop;
		if (event) {
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = event.pageX + settings(current).left;
			top = event.pageY + settings(current).top;
			var right='auto';
			if (settings(current).positionLeft) {
				right = $(window).width() - left;
				left = 'auto';
			}
			helper.parent.css({
				left: left,
				right: right,
				top: top
			});
		}
		
		var v = viewport(),
			h = helper.parent[0];
		// check horizontal position
		if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
			left -= h.offsetWidth + 20 + settings(current).left;
			helper.parent.css({left: left + 'px'}).addClass("viewport-right");
		}
		// check vertical position
		if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
			top -= h.offsetHeight + 20 + settings(current).top;
			helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
		}
	}
	
	function viewport() {
		return {
			x: $(window).scrollLeft(),
			y: $(window).scrollTop(),
			cx: $(window).width(),
			cy: $(window).height()
		};
	}
	
	// hide helper and restore added classes and the title
	function hide(event) {
		if($.tooltip.blocked)
			return;
		// clear timeout if possible
		if(tID)
			clearTimeout(tID);
		// no more current element
		current = null;
		
		var tsettings = settings(this);
		function complete() {
			helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
		}
		if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
			if (helper.parent.is(':animated'))
				helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
			else
				helper.parent.stop().fadeOut(tsettings.fade, complete);
		} else
			complete();
		
		if( settings(this).fixPNG )
			helper.parent.unfixPNG();
	}
	
})(jQuery);
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2446 $
 *
 * Version 2.1.1
 */

(function($){

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE6 
 * and adds a class to the iframe called 'bgiframe'. The iframe
 * is appeneded as the first child of the matched element(s) 
 * with a tabIndex and zIndex of -1.
 * 
 * By default the plugin will take borders, sized with pixel units,
 * into account. If a different unit is used for the border's width,
 * then you will need to use the top and left settings as explained below.
 *
 * NOTICE: This plugin has been reported to cause perfromance problems
 * when used on elements that change properties (like width, height and
 * opacity) a lot in IE6. Most of these problems have been caused by 
 * the expressions used to calculate the elements width, height and 
 * borders. Some have reported it is due to the opacity filter. All 
 * these settings can be changed if needed as explained below.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @param Map settings Optional settings to configure the iframe.
 * @option String|Number top The iframe must be offset to the top
 * 		by the width of the top border. This should be a negative 
 *      number representing the border-top-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-top-width if it is in pixels.
 * @option String|Number left The iframe must be offset to the left
 * 		by the width of the left border. This should be a negative 
 *      number representing the border-left-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-left-width if it is in pixels.
 * @option String|Number width This is the width of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetWidth.
 * @option String|Number height This is the height of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetHeight.
 * @option Boolean opacity This is a boolean representing whether or not
 * 		to use opacity. If set to true, the opacity of 0 is applied. If
 *		set to false, the opacity filter is not applied. Default: true.
 * @option String src This setting is provided so that one could change 
 *		the src of the iframe to whatever they need.
 *		Default: "javascript:false;"
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);/*
 *
 *	jQuery Timer plugin v0.1
 *		Matt Schmidt [http://www.mattptr.net]
 *
 *	Licensed under the BSD License:
 *		http://mattptr.net/license/license.txt
 *
 */
 
 jQuery.timer = function (interval, callback)
 {
 /**
  *
  * timer() provides a cleaner way to handle intervals  
  *
  *	@usage
  * $.timer(interval, callback);
  *
  *
  * @example
  * $.timer(1000, function (timer) {
  * 	alert("hello");
  * 	timer.stop();
  * });
  * @desc Show an alert box after 1 second and stop
  * 
  * @example
  * var second = false;
  *	$.timer(1000, function (timer) {
  *		if (!second) {
  *			alert('First time!');
  *			second = true;
  *			timer.reset(3000);
  *		}
  *		else {
  *			alert('Second time');
  *			timer.stop();
  *		}
  *	});
  * @desc Show an alert box after 1 second and show another after 3 seconds
  *
  * 
  */

	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
 };
 /*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.2",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/*
 * jQuery UI Accordion 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.accordion", {

	_init: function() {

		var o = this.options, self = this;
		this.running = 0;

		// if the user set the alwaysOpen option on init
		// then we need to set the collapsible option
		// if they set both on init, collapsible will take priority
		if (o.collapsible == $.ui.accordion.defaults.collapsible &&
			o.alwaysOpen != $.ui.accordion.defaults.alwaysOpen) {
			o.collapsible = !o.alwaysOpen;
		}

		if ( o.navigation ) {
			var current = this.element.find("a").filter(o.navigationFilter);
			if ( current.length ) {
				if ( current.filter(o.header).length ) {
					this.active = current;
				} else {
					this.active = current.parent().parent().prev();
					current.addClass("ui-accordion-content-active");
				}
			}
		}

		this.element.addClass("ui-accordion ui-widget ui-helper-reset");
		
		// in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix
		if (this.element[0].nodeName == "UL") {
			this.element.children("li").addClass("ui-accordion-li-fix");
		}

		this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all")
			.bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); })
			.bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); })
			.bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); })
			.bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); });

		this.headers
			.next()
				.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");

		this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");
		this.active.next().addClass('ui-accordion-content-active');

		//Append icon elements
		$("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers);
		this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected);

		// IE7-/Win - Extra vertical space in lists fixed
		if ($.browser.msie) {
			this.element.find('a').css('zoom', '1');
		}

		this.resize();

		//ARIA
		this.element.attr('role','tablist');

		this.headers
			.attr('role','tab')
			.bind('keydown', function(event) { return self._keydown(event); })
			.next()
			.attr('role','tabpanel');

		this.headers
			.not(this.active || "")
			.attr('aria-expanded','false')
			.attr("tabIndex", "-1")
			.next()
			.hide();

		// make sure at least one header is in the tab order
		if (!this.active.length) {
			this.headers.eq(0).attr('tabIndex','0');
		} else {
			this.active
				.attr('aria-expanded','true')
				.attr('tabIndex', '0');
		}

		// only need links in taborder for Safari
		if (!$.browser.safari)
			this.headers.find('a').attr('tabIndex','-1');

		if (o.event) {
			this.headers.bind((o.event) + ".accordion", function(event) { return self._clickHandler.call(self, event, this); });
		}

	},

	destroy: function() {
		var o = this.options;

		this.element
			.removeClass("ui-accordion ui-widget ui-helper-reset")
			.removeAttr("role")
			.unbind('.accordion')
			.removeData('accordion');

		this.headers
			.unbind(".accordion")
			.removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top")
			.removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex");

		this.headers.find("a").removeAttr("tabindex");
		this.headers.children(".ui-icon").remove();
		var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");
		if (o.autoHeight || o.fillHeight) {
			contents.css("height", "");
		}
	},
	
	_setData: function(key, value) {
		if(key == 'alwaysOpen') { key = 'collapsible'; value = !value; }
		$.widget.prototype._setData.apply(this, arguments);	
	},

	_keydown: function(event) {

		var o = this.options, keyCode = $.ui.keyCode;

		if (o.disabled || event.altKey || event.ctrlKey)
			return;

		var length = this.headers.length;
		var currentIndex = this.headers.index(event.target);
		var toFocus = false;

		switch(event.keyCode) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[(currentIndex + 1) % length];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[(currentIndex - 1 + length) % length];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				return this._clickHandler({ target: event.target }, event.target);
		}

		if (toFocus) {
			$(event.target).attr('tabIndex','-1');
			$(toFocus).attr('tabIndex','0');
			toFocus.focus();
			return false;
		}

		return true;

	},

	resize: function() {

		var o = this.options, maxHeight;

		if (o.fillSpace) {
			
			if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); }
			maxHeight = this.element.parent().height();
			if($.browser.msie) { this.element.parent().css('overflow', defOverflow); }
	
			this.headers.each(function() {
				maxHeight -= $(this).outerHeight();
			});

			var maxPadding = 0;
			this.headers.next().each(function() {
				maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
			}).height(Math.max(0, maxHeight - maxPadding))
			.css('overflow', 'auto');

		} else if ( o.autoHeight ) {
			maxHeight = 0;
			this.headers.next().each(function() {
				maxHeight = Math.max(maxHeight, $(this).outerHeight());
			}).height(maxHeight);
		}

	},

	activate: function(index) {
		// call clickHandler with custom event
		var active = this._findActive(index)[0];
		this._clickHandler({ target: active }, active);
	},

	_findActive: function(selector) {
		return selector
			? typeof selector == "number"
				? this.headers.filter(":eq(" + selector + ")")
				: this.headers.not(this.headers.not(selector))
			: selector === false
				? $([])
				: this.headers.filter(":eq(0)");
	},

	_clickHandler: function(event, target) {

		var o = this.options;
		if (o.disabled) return false;

		// called only when using activate(false) to close all parts programmatically
		if (!event.target && o.collapsible) {
			this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
				.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
			this.active.next().addClass('ui-accordion-content-active');
			var toHide = this.active.next(),
				data = {
					options: o,
					newHeader: $([]),
					oldHeader: o.active,
					newContent: $([]),
					oldContent: toHide
				},
				toShow = (this.active = $([]));
			this._toggle(toShow, toHide, data);
			return false;
		}

		// get the click target
		var clicked = $(event.currentTarget || target);
		var clickedIsActive = clicked[0] == this.active[0];

		// if animations are still active, or the active header is the target, ignore click
		if (this.running || (!o.collapsible && clickedIsActive)) {
			return false;
		}

		// switch classes
		this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
			.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
		this.active.next().addClass('ui-accordion-content-active');
		if (!clickedIsActive) {
			clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top")
				.find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected);
			clicked.next().addClass('ui-accordion-content-active');
		}

		// find elements to show and hide
		var toShow = clicked.next(),
			toHide = this.active.next(),
			data = {
				options: o,
				newHeader: clickedIsActive && o.collapsible ? $([]) : clicked,
				oldHeader: this.active,
				newContent: clickedIsActive && o.collapsible ? $([]) : toShow.find('> *'),
				oldContent: toHide.find('> *')
			},
			down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] );

		this.active = clickedIsActive ? $([]) : clicked;
		this._toggle(toShow, toHide, data, clickedIsActive, down);

		return false;

	},

	_toggle: function(toShow, toHide, data, clickedIsActive, down) {

		var o = this.options, self = this;

		this.toShow = toShow;
		this.toHide = toHide;
		this.data = data;

		var complete = function() { if(!self) return; return self._completed.apply(self, arguments); };

		// trigger changestart event
		this._trigger("changestart", null, this.data);

		// count elements to animate
		this.running = toHide.size() === 0 ? toShow.size() : toHide.size();

		if (o.animated) {

			var animOptions = {};

			if ( o.collapsible && clickedIsActive ) {
				animOptions = {
					toShow: $([]),
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: o.autoHeight || o.fillSpace
				};
			} else {
				animOptions = {
					toShow: toShow,
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: o.autoHeight || o.fillSpace
				};
			}

			if (!o.proxied) {
				o.proxied = o.animated;
			}

			if (!o.proxiedDuration) {
				o.proxiedDuration = o.duration;
			}

			o.animated = $.isFunction(o.proxied) ?
				o.proxied(animOptions) : o.proxied;

			o.duration = $.isFunction(o.proxiedDuration) ?
				o.proxiedDuration(animOptions) : o.proxiedDuration;

			var animations = $.ui.accordion.animations,
				duration = o.duration,
				easing = o.animated;

			if (!animations[easing]) {
				animations[easing] = function(options) {
					this.slide(options, {
						easing: easing,
						duration: duration || 700
					});
				};
			}

			animations[easing](animOptions);

		} else {

			if (o.collapsible && clickedIsActive) {
				toShow.toggle();
			} else {
				toHide.hide();
				toShow.show();
			}

			complete(true);

		}

		toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur();
		toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus();

	},

	_completed: function(cancel) {

		var o = this.options;

		this.running = cancel ? 0 : --this.running;
		if (this.running) return;

		if (o.clearStyle) {
			this.toShow.add(this.toHide).css({
				height: "",
				overflow: ""
			});
		}

		this._trigger('change', null, this.data);
	}

});


$.extend($.ui.accordion, {
	version: "1.7.2",
	defaults: {
		active: null,
		alwaysOpen: true, //deprecated, use collapsible
		animated: 'slide',
		autoHeight: true,
		clearStyle: false,
		collapsible: false,
		event: "click",
		fillSpace: false,
		header: "> li > :first-child,> :not(li):even",
		icons: {
			header: "ui-icon-triangle-1-e",
			headerSelected: "ui-icon-triangle-1-s"
		},
		navigation: false,
		navigationFilter: function() {
			return this.href.toLowerCase() == location.href.toLowerCase();
		}
	},
	animations: {
		slide: function(options, additions) {
			options = $.extend({
				easing: "swing",
				duration: 300
			}, options, additions);
			if ( !options.toHide.size() ) {
				options.toShow.animate({height: "show"}, options);
				return;
			}
			if ( !options.toShow.size() ) {
				options.toHide.animate({height: "hide"}, options);
				return;
			}
			var overflow = options.toShow.css('overflow'),
				percentDone,
				showProps = {},
				hideProps = {},
				fxAttrs = [ "height", "paddingTop", "paddingBottom" ],
				originalWidth;
			// fix width before calculating height of hidden element
			var s = options.toShow;
			originalWidth = s[0].style.width;
			s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - (parseInt(s.css("borderLeftWidth"),10) || 0) - (parseInt(s.css("borderRightWidth"),10) || 0) );
			
			$.each(fxAttrs, function(i, prop) {
				hideProps[prop] = 'hide';
				
				var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/);
				showProps[prop] = {
					value: parts[1],
					unit: parts[2] || 'px'
				};
			});
			options.toShow.css({ height: 0, overflow: 'hidden' }).show();
			options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{
				step: function(now, settings) {
					// only calculate the percent when animating height
					// IE gets very inconsistent results when animating elements
					// with small values, which is common for padding
					if (settings.prop == 'height') {
						percentDone = (settings.now - settings.start) / (settings.end - settings.start);
					}
					
					options.toShow[0].style[settings.prop] =
						(percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit;
				},
				duration: options.duration,
				easing: options.easing,
				complete: function() {
					if ( !options.autoHeight ) {
						options.toShow.css("height", "");
					}
					options.toShow.css("width", originalWidth);
					options.toShow.css({overflow: overflow});
					options.complete();
				}
			});
		},
		bounceslide: function(options) {
			this.slide(options, {
				easing: options.down ? "easeOutBounce" : "swing",
				duration: options.down ? 1000 : 200
			});
		},
		easeslide: function(options) {
			this.slide(options, {
				easing: "easeinout",
				duration: 700
			});
		}
	}
});

})(jQuery);
var STATIC_CSS_LINK = 'css';
var checkboxesPerRow = Array();
var objectToFade = "";
var timeoutToFade = "";
var fadeObject = false;
var ep_rotate_link_clicked = false; //roate link im Phototool

function ge(what){
	return document.getElementById(what);
}

$(document).ready(function(){
	// ATTENTION: DO NOT REMOVE THE FOLLOWING COMMENT!
	/*if ( $('.profile_table').size() < 1)
	{
	init_testHover();
	}*/
	magazinLayerHeight();
	initTooltip();
	
	/* Info-Box, z.b. bei den Formularen*/
	
	$('.ep_invisisbleinfobox_bottom').bgiframe();
	$('.ep_invisisbleinfobox').bgiframe();
	
	/* LandingPage Bildwechsel*/
	if ($('#changing_img').size() > 0){
	   window.setTimeout("changeImg('#changing_img', '" + EMN.WebappPrefix + "/gfx/basic/landingpage/woman2_02.jpg')", 3000);
	   window.setTimeout("changeImg('#changing_img', '" + EMN.WebappPrefix + "/gfx/basic/landingpage/woman2_01.jpg')", 5000);
	}
	
	/* Magazin Accordion-Menü*/
	if ($('#ep_top_article').size() > 0){
		$("#ep_top_article").accordion({
			header: '.ep_top_title',
			event: 'mouseover'
		});
	}
});

function changeInputType(dies,to){
	dies.type=to;
}

// Berechnung der Höhe der Magazin-TEaser, ob dem umschließenden Link auf die Höhe des Inhalts zu bringen.
function magazinLayerHeight()
{
	if ($('.ep_magazin_layer').size() > 0)
	{
		$('.ep_magazin_layer').each(function()
			{
			var height= $(this).parent().height();
			
			$(this).css('height', height);
			
			$("#"+this.id +' a img').css('height',height);
			}
		);
	}


}

// Initialsirierung des Tooltips in allen varianten
function initTooltip()
{
	if ($('.ep_tool_icon').size() > 0)
	{
		if ($('.ep_negative_choose').size() <= 0)
		{
		
			$('.ep_tool_icon').tooltip(
			{
				track: true, 
			    delay: 0, 
			    showURL: false, 
			    opacity: 1, 
			    fixPNG: true, 
			    top: 10, 
    			left: 5, 
			    extraClass: "ep_tooltip"
			    
			});
		}
		else
		{
		
			$('.ep_negative_choose .ep_tool_icon').tooltip(
			{
				track: true, 
			    delay: 0, 
			    showURL: false, 
			    opacity: 1, 
			    fixPNG: true, 
			    top: 10, 
    			left: 5,
			    extraClass: "ep_tooltip_neg"
			   
			});
		}
	}
	
	if ($('.ep_tool_icon_blue').size() > 0)
	{
		$('.ep_tool_icon_blue').tooltip(
			{
				track: true, 
			    delay: 0, 
			    showURL: false, 
			    opacity: 1, 
			    fixPNG: true, 
			    top: 10, 
    			left: 5, 
			    extraClass: "ep_tooltip_blue"			    
			});
	}

}


// Initialisierung der Hover-Effekte für den Test (Wohnen, Vorlieben etc.)
function init_testHover()
{
	if ($('.ep_test_layer').size() > 0 )
	{
	
		$('.ep_test_layer').each(function()
			{
			var height= $(this).parent().height();		
			
			var imgHeight = height-6;
			$(this).css('height', height);
			
			$("#"+this.id +' img').css('height', imgHeight);
			}
		);
		
		if ($('.ep_negative_choose').size() > 0) // Wenn Nevgativ-Auswahl -> für Rote Ränder
		{
		
			$('.ep_choosen_layer').each(function()
				{
				var height= $(this).parent().height();
				height = height-4;
				var imgHeight = height-10;
				
				$(this).css('height', height);
				
				$("#"+this.id +' img').css('height', imgHeight);
				}
			);			
			var COLOR='#C60000';		// Red
		}
		else  // Wenn nicht negativ-Auswahl
		{
			var COLOR='#269100';		// Green
		
		}
		
		$('.ep_test_layer').hover(function()
			{
				
				var width= $(this).parent().width();	
				
				if ($(this).attr('class') == 'ep_test_layer ep_active')
				{
					width = width-10;
					$(this).css('border','5px solid '+ COLOR);
					$(this).css('width', width+'px');	
				}
				else
				{
					$(this).css('border','3px solid '+ COLOR);	
				}
			},
			function()
			{
				if ($(this).attr('class') == 'ep_test_layer ep_active')
				{
					//$(this).css('border','5px  transparent');
					//$(this).css('width', '205px');	
				}
				else
				{
					$(this).css('border','3px transparent');	
				}
			}
			
			);
		
			$('.ep_test_layer').click(function()
				{
					
					var check = count_selected('0');
					var width= $(this).parent().width();
						
						if ($(this).attr('class') == 'ep_test_layer')
						{
							if (check ==true )
							{
								width = width-10;
								$(this).attr('class', 'ep_test_layer ep_active');
								$(this).css('border','5px solid '+ COLOR);
								$(this).css('width', width+'px');
								var height= $(this).height();
								height = height-4;
								$(this).height(height);
								var input = $(this).prev().prev();
								
								$('#'+ this.id +' img').attr('title', 'abw&auml;hlen');
								
								
								$(input).attr('value', 1);
								var head= $(this).prev().prev().prev().prev();
								$(head).css('color', '#269100 !important');
							}
							
						}
						else
						{
							width = width-6;
							$(this).attr('class', 'ep_test_layer');
							$(this).css('border','3px solid '+ COLOR);
							$(this).css('width', width+'px');
							var height= $(this).height();
							
							
							height = height+4;
							
							$(this).height(height);
							var input = $(this).prev().prev();
							
							$('#'+ this.id +' img').attr('title', 'ausw&auml;hlen');
							
							
							$(input).attr('value', 0);
							var head= $(this).prev().prev().prev().prev();
							$(head).css('color', '#534F48 !important');
								
						}
						
						
						if ($('.ep_negative_choose').size() <= 0)
							{
							
								$('#'+ this.id +' img').tooltip(
								{
									track: true, 
								    delay: 0, 
								    showURL: false, 
								    opacity: 1, 
								    fixPNG: true, 
								    top: 10, 
					    			left: 5, 
								    extraClass: "ep_tooltip"
								    
								});
							}
							else
							{
							
								$('#'+ this.id +' img').tooltip(
								{
									track: true, 
								    delay: 0, 
								    showURL: false, 
								    opacity: 1, 
								    fixPNG: true, 
								    top: 10, 
					    			left: 5,
								    extraClass: "ep_tooltip_neg"
								   
								});
							}
						
						
						
						
						
						if ($('.ep_testcontainer .ep_active').size() !='')
						{
							$('#ep_choose_count').html($('.ep_testcontainer .ep_active').size());
						}
						else
						{
							$('#ep_choose_count').html('0');
						}					
				}
			);		
	}
}


/* Test Wohnen: Zählen der ep_activen Fenster*/
function count_selected(number)
{
	if (number == 0)
	{
	var choosen_number = $('.ep_testcontainer .ep_active').size()+1;
	}
	else
	{
	var choosen_number = 2;
	}
	var ep_max_number = $('#ep_max_number').html();
	
	//console.debug(choosen_number + '-' + ep_max_number);
	
	if (choosen_number <= ep_max_number)
	{
		
		return true;
	}
	else
	{
		return false;
		
	}

}

// Wechseln der Navigation - Highlight
function toggleNav(direction,dies){
	if(direction==1)
		$(dies).addClass('ep_hover');
	else if(direction == 0)
		$(dies).removeClass('ep_hover');		
}

function ep_activeNav(dies){
	$('#ep_mainnav li').removeClass('ep_active ep_hover');
	$('#ep_mainnav li').mouseover(function(){
		toggleNav(1,this);
	});
	$(dies).addClass('ep_active');
	dies.onmouseover = "";
}


/* Funktionen für die Buttons - Highlight */

function highlightButton (element, pathOuter, pathInner) {
	$('#' + element + ' .ep_outerspan').css('background-image', 'url(' + pathOuter + ')');
	$('#' + element + ' .ep_innerspan').css('background-image', 'url(' + pathInner + ')');
    $('#' + element).removeClass("ep_btn_dehighlight");
    $('#' + element).addClass("ep_btn_highlight");
}

function DehighlightButton (element, pathOuter, pathInner) {
	highlightButton (element, pathOuter, pathInner);
    $('#' + element).removeClass("ep_btn_highlight");
    $('#' + element).addClass("ep_btn_dehighlight");
}

function highlightRedButton (element) {
	highlightButton (element, redButton[2], redButton[3]);
}

function DehighlightRedButton (element) {
	DehighlightButton (element, redButton[0], redButton[1]);
}

function highlightGreenButton (element) {
	highlightButton (element, greenButton[2], greenButton[3]);
}

function DehighlightGreenButton (element) {
	DehighlightButton (element, greenButton[0], greenButton[1]);
}

function highlightBlueButton (element, context) {
	if(context != null){
		$('#' + element ).css('background-image', 'url(' + blueButton_login[1]+')');
	}else{
		$('#' + element ).css('background-image', 'url(' + blueButton[1]+')');	
	}	
}

function DehighlightBlueButton (element, context) {
	if(context != null){
		$('#' + element ).css('background-image', 'url(' + blueButton_login[0]+')');
	}else{
		$('#' + element ).css('background-image', 'url(' + blueButton[0]+')');
	}
}

function highlightGreyButton (element) {
	highlightButton (element, greyButton[2], greyButton[3]);
}

function DehighlightGreyButton (element) {
	DehighlightButton (element, greyButton[0], greyButton[1]);
}

function highlightRedButtonS (element) {
	highlightButton (element, redButtonS[2], redButtonS[3]);
}

function DehighlightRedButtonS (element) {
	DehighlightButton (element, redButtonS[0], redButtonS[1]);
}

function highlightGreyButtonS (element) {
	highlightButton (element, greyButtonS[2], greyButtonS[3]);
}

function DehighlightGreyButtonS (element) {
	DehighlightButton (element, greyButtonS[0], greyButtonS[1]);
}

function highlightGreenButtonS (element) {
	highlightButton (element, greenButtonS[2], greenButtonS[3]);
}

function DehighlightGreenButtonS (element) {
	DehighlightButton (element, greenButtonS[0], greenButtonS[1]);
}

function highlightBlueButtonL (element) {
	highlightButton (element, blueButton[2], blueButton[3]);
}

function DehighlightBlueButtonL (element) {
	DehighlightButton (element, blueButton[0], blueButton[1]);
}

function highlightRedGreyButtonS (element) {
	$('#' + element + ' .ep_outerspan').css('background-image', 'url(' + redGreyButtonS[2]+')');
	$('#' + element + ' .ep_innerspan').css('background-image', 'url(' + redGreyButtonS[3]+')');
}

function DehighlightRedGreyButtonS (element) {
	$('#' + element + ' .ep_outerspan').css('background-image', 'url(' + redGreyButtonS[0]+')');
	$('#' + element + ' .ep_innerspan').css('background-image', 'url(' + redGreyButtonS[1]+')');
}

function highlightRedGoldButtonS (element) {
	$('#' + element + ' .ep_outerspan').css('background-image', 'url(' + redGoldButtonS[2]+')');
	$('#' + element + ' .ep_innerspan').css('background-image', 'url(' + redGoldButtonS[3]+')');
}

function DehighlightRedGoldButtonS (element) {
	$('#' + element + ' .ep_outerspan').css('background-image', 'url(' + redGoldButtonS[0]+')');
	$('#' + element + ' .ep_innerspan').css('background-image', 'url(' + redGoldButtonS[1]+')');
}

/* Wechseln der Tabs*/
function changeMultiTab (tab, element)
{
	$('#'+tab + ' .ep_tab_container').css("display", "none"); // Alle container werden unsichtbar
	$('#'+tab + '_' + element +'').css("display", "block"); // Das auserwählte container wird sichtbar
	
	
	//console.debug(tab+', '+element);
	$('#'+tab + '_list li').removeClass("ep_active"); // Alle LI's werden 'normal'
	$('#'+tab + '_' + element +'_link').addClass("ep_active"); // Das auserwählte LI wird ep_active
	
	
}

// Einfacher Bildwechsel
function changeImg(element, pic)
{
	$(element).attr('src', pic);

}


function toggleTeaserContent(element)
{
	if($('#'+element+'_arrow').attr('src').indexOf('arrow_close.gif')!=-1)
	{
		//$('#'+element+'_arrow').attr('src', EMN.WebappPrefix + "/gfx/basic/icons/arrow_open.gif");
		document.getElementById(element+'_arrow').src = EMN.WebappPrefix +  "/gfx/basic/icons/arrow_open.gif"
		if($.browser.msie && $.browser.version <= 6)
		{
			$('#'+element+'_content').hide();
		}
		else
		{
		$('#'+element+'_content').animate(
            {
                height: 'toggle'
            }
            );
        }
		
	}
	else{
		$	('#'+element+'_arrow').attr('src',  + EMN.WebappPrefix + "/gfx/basic/icons/arrow_close.gif");	
		
		if($.browser.msie && $.browser.version <= 6)
		{
			$('#'+element+'_content').show();
		}
		else
		{
			$('#'+element+'_content').animate(
            {
                height: 'toggle'
            }
            );
        }
	}

}


function toogleFavorit(element)
{
	var src = element.src; 
	if(element.src.indexOf('yes')!=-1)
	{
		var new_src= src.replace(/yes/, "no");
		element.title="zu den Favoriten hinzuf&uuml;gen";
	}
	else{
		$
		var new_src= src.replace(/no/, "yes");
		element.title="aus Favoriten entfernen";
	}
	element.src = new_src;
	$(element).tooltip(
			{
				track: true, 
			    delay: 0, 
			    showURL: false, 
			    opacity: 1, 
			    fixPNG: true, 
			    top: 10, 
    			left: 5, 
			    extraClass: "ep_tooltip_blue"			    
			});
	

}


function changeMatchCheckBox(dies){
	row= dies.id.substring(6,dies.id.indexOf('_'));	
	if(null != checkboxesPerRow[row])
		checkboxesPerRow[row].src = EMN.WebappPrefix + "/gfx/basic/icons/checkbox_off.gif";
	checkboxesPerRow[row] = dies;
	if(dies.src.indexOf('off.gif')!=-1){
		dies.src = EMN.WebappPrefix + "/gfx/basic/icons/checkbox_on.gif";
	}
	else{
		dies.src = EMN.WebappPrefix + "/gfx/basic/icons/checkbox_off.gif";		
	}
	document.getElementById('ep_row'+row).value=dies.id.substring(dies.id.indexOf('_')+1,dies.id.length);
	
}

function refresh_suggest(val){
	$('#ep_partner_suggest p').removeClass('highlight');
	$('#ep_partner_suggest p').removeClass('bold');
	
	if(val.indexOf('fav')==-1){
		$('#ep_partner_suggest .fav p img').each(function(i){
			if(this.src.indexOf('yes')!=-1){
				this.src = EMN.WebappPrefix + '/gfx/basic/icons/30x30_fav_yes_w.gif';
			}
			else{
				this.src = EMN.WebappPrefix + '/gfx/basic/icons/30x30_fav_no_w.gif';
			}
		});
	}
	
	
	
	if(val.indexOf('mp')!=-1){	
		$('#ep_partner_suggest #mp p').addClass('highlight bold');
		$('#ep_partner_suggest .mp p').addClass('highlight');
	}
	else if(val.indexOf('date')!=-1){	
		$('#ep_partner_suggest #date p').addClass('highlight bold');
		$('#ep_partner_suggest .date p').addClass('highlight');
	}
	else if(val.indexOf('age')!=-1){	
		$('#ep_partner_suggest #age p').addClass('highlight bold');
		$('#ep_partner_suggest .age p').addClass('highlight');
	}
	else if(val.indexOf('rate')!=-1){	
		$('#ep_partner_suggest #rate p').addClass('highlight bold');
		$('#ep_partner_suggest .rate p').addClass('highlight');
	}
	else if(val.indexOf('region')!=-1){	
		$('#ep_partner_suggest #region p').addClass('highlight bold');
		$('#ep_partner_suggest .region p').addClass('highlight');
	}
	else if(val.indexOf('mess')!=-1){    
        $('#ep_partner_suggest #messages p').addClass('highlight bold');
        $('#ep_partner_suggest .messages p').addClass('highlight');
    }
	else if(val.indexOf('fav')!=-1){	
		$('#ep_partner_suggest #fav p').addClass('highlight bold');
		$('#ep_partner_suggest .fav p').addClass('highlight');
		$('#ep_partner_suggest .fav p img').each(function(i){
			if(this.src.indexOf('yes')!=-1){
				this.src = EMN.WebappPrefix + '/gfx/basic/icons/30x30_fav_yes_bl.gif';
			}
			else{
				this.src = EMN.WebappPrefix + '/gfx/basic/icons/30x30_fav_no_bl.gif';
			}
		});
		
	}
}
//Minimiert oder maximiert den Inhalt eines Teasers entsprechend seines Zustandes
function minimize_maximize_teaser(dies,content){
	if(document.getElementById(content).style.display == "none"){
		document.getElementById(content).style.display = "block";
	}
	else{
		document.getElementById(content).style.display = "none";
	}
}


//Sorgt dafür, dass das übergebene Element blinkt
function flash_cockpit(dies,timeout){
		objectToFade = dies;
		timeoutToFade = timeout;
		if(!fadeObject)
			blink_element();
		
		
}

//Stop Flashing Content
function unflash_cockpit(){
	fadeObject = false;
}

function blink_element(){
	fadeObject = true;
	if(objectToFade.style.visibility != "hidden")
		objectToFade.style.visibility = "hidden";
	else
		objectToFade.style.visibility = "visible";	
	if(fadeObject)
		window.setTimeout("blink_element()",timeoutToFade)
}




// öffnen der Thickbox, berechnen der Position etc,
function openThickbox(element)
{
	
	var TB_WIDTH = $('#' + element + '_TBinner').width();
	var TB_HEIGHT = $('#' + element + '_TBinner').height();
	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("ep_TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("#ep_TB_overlay_messageLayer").click(closeThickbox(element));
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				
				$("#ep_TB_overlay_messageLayer").click(closeThickbox(element));
			}
		}
	
	var pagesize = tb_getPageSize();
	var page_x = pagesize[0] - 150;
	var page_y = pagesize[1] - 150;	
	
	$('#ep_TB_overlay_messageLayer').bgiframe();
	$("#ep_TB_overlay_messageLayer").show();
   
    $('#' + element + '_TBinner').css({marginLeft: '-' + parseInt(( TB_WIDTH / 2),10) + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$('#' + element + '_TBinner').css({marginTop: '-' + parseInt(( TB_HEIGHT / 2 +40),10) + 'px'});
	}
    
    $('#' + element + '_TBinner').show();
    
    
}


// Thickbox schliessen
function closeThickbox(element)
{
	$("#ep_TB_overlay_messageLayer").hide();
    $('#' + element + '_TBinner').hide();
     if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}

}

// Berechnung der Fensterhöhe
function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

// anzeigen des Textes für die Flash-Applikation auf der Startseite 
function initialFlashText(status)
{
	//Wenn 0 als Wert übergeben wird, dann werden die Textboxen komplett ausgeblendet -> Beim Beenden und als Startwert
	//console.debug(status);
	if(status == 0) 
	{
		$('#ep_video_teaser_desc').hide();
		//$('#video_teaser_main').css('height', 'auto');
	}
	else //Wenn 1 als Wert übergeben wird, dann werden die Textboxen komplett EINgeblendet -> beim Starten des Films
	{
		//$('#video_teaser_main').css('height', '312px !important;');
		//$('#video_teaser_main').css('overflow', 'hidden');
		$('#ep_video_teaser_desc').show();
		//$('#video_teaser_desc').css('height', '104px');
		
	}

}

function showFlashText (element)
{
	$('#ep_magazin_box_start').hide();
	$('.ep_flashtext').hide();
	$('#ep_flash_text_'+element).show();
}


// Öffnen des Phototools im Popup und setzen des Focus auf das Popup.
function openPhotoTool()
{
	var phototool = window.open('phototool.php', 'Phototool','width=705,height=616, resizable=yes , scrollbars=yes' );
	phototool.focus();
}

// Öffnen der Erklärung bei Analyse 
function openDesc()
{
	var desc = window.open('popup_desc.php', 'Erklaerung', 'width=455, height= 420, resizable=yes , scrollbars=yes' );
	desc.focus();
}


// Hover Funktion der Thumbnails im Profil. Bei Hover wird das mainpic entsprechend ausgetauscht
function showThumbnailAsMain(thumb){
    bigThumbSrc = thumb.src.replace(/small/,"big");
    $('#ep_profile_mainpic img:first').attr("src",bigThumbSrc);
    $('#ep_profile_pics .ep_small_pic img').css("border","2px solid #fff"); // alle borders resetten
    $(thumb).css("border","2px solid #DEDEDE");//die aktuell gehoverte bordern
}

// Verwaltet die ep_hovers, mouseouts und onclicks für die Funktionsbutton im phototool
// WICHTIG: mit mode= 0 aufrufen, wenn der AJAX-REquest für das Bild drehen abgarbeitet ist, um dann Icon und Schriftfarbe zurück zusetzen.
function change_phototool_rotate(mode){
	//onclickin || onclickout
	if(mode==2 || mode==3){ 
		// bei clickout, ursprungszustand wiederherstellen 
		if(mode==3){
			ge('ep_rotate_icon').src= EMN.WebappPrefix + '/gfx/basic/icons/btn_drehen_blue.gif'
			ge('ep_rotate_link').style.color="#004784;"
		}
		// clickin: alles rot machen
		else{
			ge('ep_rotate_icon').src= EMN.WebappPrefix + '/gfx/basic/icons/btn_drehen_red.gif'
			ge('ep_rotate_link').style.color="#c60000;"
		}
		
		ep_rotate_link_clicked = !ep_rotate_link_clicked;
		//neben der Anzeige selbst, müssen noch die eventhandler angepasst werden
		if(ep_rotate_link_clicked){
			ge('ep_rotate_link').onclick = function(){change_phototool_rotate(3);}
			ge('ep_rotate_link').onmouseout = function(){change_phototool_rotate(-1);}; //deaktivieren, damit es im aktivzustand nicht ausgelöst wird.
		}
		else{
			ge('ep_rotate_link').onclick = function(){change_phototool_rotate(2);}
			ge('ep_rotate_link').onmouseout = function(){change_phototool_rotate(0);};
		}
		
	}
	//ep_hover
	else if(mode==1){ 
		ge('ep_rotate_icon').src= EMN.WebappPrefix + '/gfx/basic/icons/btn_drehen_red.gif'
		ge('ep_rotate_link').style.color="#c60000;"
	}
	//mouseout
	else if(mode==0){ 
		ge('ep_rotate_icon').src= EMN.WebappPrefix + '/gfx/basic/icons/btn_drehen_blue.gif'
		ge('ep_rotate_link').style.color="#004784;"
	}
}

function edit_in_place(row)
{	
	if(typeof(row)=="string"){
		row = new Array(row);
	}
	for(i=0;i<row.length;i++){				
			$("#"+row[i]).hide();
			$("#"+row[i]+"_hidden").show();
			$("#"+row[i]+"_hidden *").show();
		//Safari Hack wegen des Umbrechens des input feldes im profil
                    if($.browser.safari){
                        $("#"+row[i]+"_hidden .inputs").css("width","310px");
                    }

		
	}
}

function close_in_place(row)
{	
	if(typeof(row)=="string"){
		row = new Array(row);
	}
	for(i=0;i<row.length;i++){
				
			$("#"+row[i]+"_hidden").hide();
			$("#"+row[i]+"_hidden *").hide();
			$("#"+row[i]).show();
		
	}
}

// Funktion zum überprüfen von select Felder
// vorerst wird nur close_in_place aufrufen
function checkSelects(row){
        close_in_place(row);
}


function checkTextBox(row,field){
    if($("#"+row+"_hidden #"+field).val()!=""){
        $("#"+row+"_form .error").css("visibility","hidden");;
        $('#'+row+"_hidden h3").removeClass('red');
        $("#"+row+"_hidden #"+field).removeClass("input_border_error_red");
        close_in_place(row);
        return true;        
    }
    else{
        $("#"+row+"_form .error").text("Bitte füllen Sie das Feld aus.");
        $("#"+row+"_form .error").css("visibility","visible");
        $('#'+row+"_hidden h3").addClass('red');  
        $("#"+row+"_hidden #"+field).addClass("input_border_error_red");      
        return false;       
    }
}

// Berechnet und aktualisiert das Alter
function calculate_age(){
    // Berechnung:
    // Aktualisierung:
    $('#the_age').val("23");
}

// Open/close der Bundesländer-Anzeige in der Sichkriterien-Seite
function toggleBL()
{
	if ($('#regions').css('display') == 'none')
	{
		$('#regions').show();
		$('#ep_bundeslaender').show();
		$('#regionslink').html('Bundesl&auml;nder ausblenden');
	
	}
	else
	{
		$('#regions').hide();
		$('#ep_bundeslaender').hide();
		$('#regionslink').html('Bundesl&auml;nder anzeigen');
	}
}

// Open/close der Bundesländer-Anzeige in der Sichkriterien-Seite
function toggleSingleBL(element)
{
	
	//console.debug ($('#ep_bundesland_'+element).css('display'));
	if ($('#regions_'+element).css('display') == 'none')
	{
		$('#regions_'+element).show();	
	
	}
	else
	{
		$('#regions_'+element).hide();	
	}
	
}

// Open/close der der NAchrichten im Postfach
function toogleMessageText(element)
{
	if ($('#message_'+element+'_sender').css('display') == 'none')
	{
		$('#message_'+element+'_sender').show();
		$('#message_'+element+'_time').show();
		if($.browser.msie && $.browser.version <= 6)
		{
		$('#message_'+element+'_longtext button').show();
		}
		$('#message_'+element+'_shorttext').animate(
            {
                height: 'toggle'
            });
		$('#message_'+element+'_longtext').animate(
            {
                height: 'toggle'
            });
		
		$('#message_'+element).attr('class', '');	
		$('#message_'+element+' ').children().removeClass('border_l_5_blue');	
		$('#message_'+element+' ').children().removeClass('bold');	
		$('#message_'+element+' .pv_userdesc a').css('font-weight','normal')
		
	}
	else
	{
		$('#message_'+element+'_sender').hide();
		$('#message_'+element+'_time').hide();
		if($.browser.msie && $.browser.version <= 6)
		{
		$('#message_'+element+'_longtext button').hide();
		}
		$('#message_'+element+'_longtext').animate(
            {
                height: 'toggle'
            });
		$('#message_'+element+'_shorttext').animate(
            {
                height: 'toggle'
            });
		
		
	}


}


function togglePicsforFree(element)
{
	if (element == 1)
	{
		$('#contactstatus_img').attr('src', EMN.WebappPrefix + '/gfx/basic/icons/kontstat_fotoyes.gif');
		$('#photo_choose_label_yes').css('font-weight', 'bold !important');
		$('#photo_choose_label_no').css('font-weight', 'normal !important');
	}
	else
	{
		$('#contactstatus_img').attr('src', EMN.WebappPrefix + '/gfx/basic/icons/kontstat_fotono.gif');
		$('#photo_choose_label_yes').css('font-weight', 'normal !important');
		$('#photo_choose_label_no').css('font-weight', 'bold !important');
	}

}


function toggleBookmark(element)
{
	if ($('#'+element).css('display') == 'none')
	{
		$('#'+element).show();	
	}
	else
	{
		$('#'+element).hide();
		
	}
}

function toggleVideoTeaser(element, width, height, path)
{
	$('.ep_video_container').hide();
	$('#ep_video_container_'+element).show();
	ClickTourNum = 0;
	$('.ep_flashtext').hide();
	var appendix = element.length < 2 ? "" : element.substr(1);
	
		if ($('#clicktour_img_w' + appendix).size() > 0 )
	    {
			 $('#clicktour_img_w' + appendix).attr('src',$('#clicktour_img_w' + appendix).attr('src').replace(/[0-9]+/, 0));
		}
		
		if ($('#clicktour_img_e' + appendix).size() > 0 )
	    {
	    	 $('#clicktour_img_e' + appendix).attr('src',$('#clicktour_img_e' + appendix).attr('src').replace(/[0-9]+/, 0));
	    }
	    
	    if ($('#clicktour_img_r' + appendix).size() > 0)
	    {
	    	 $('#clicktour_img_r' + appendix).attr('src',$('#clicktour_img_r' + appendix).attr('src').replace(/[0-9]+/, 0));
	    }
		
	if ($('#clicktour_img_w' + appendix).size() > 0  || $('#clicktour_img_r' + appendix).size() > 0  || $('#clicktour_img_e' + appendix).size() > 0)	
	{	
		$("#clicktour_left_"+element).hide();
	 	$("#clicktour_left_back_"+element).hide();
	 	$("#clicktour_right_"+element).hide();
	 	$("#clicktour_right_back_"+element).hide();
	 	$("#clicktour_link_"+element).show();
		
	}
	// choose player config
	if(element == 'r'){
		initFlashPlayer("/static/flash/player/player.swf", "flashplayerMain_rundgang", "445", "376",
				"debug=false"+
				"&controlbar=none"+
				"&skin=/static/flash/skins/playerSkin_startseite.swf"+
				"&autostart=true"+
				"&screencolor=#ffffff"+
				"&streamer=rtmp://elitepartner-streaming.corpex-streaming.de/emn/"+
				"&httpfallback=5,http://elitepartner-fallback.corpex-streaming.de/emn/"+
				"&file=/static/flash/playlists/playlist-rundgang.xml"+
				"&bwcheck=150,1000"+
				"&bwanimation=true"+
				"&icons=true"+
				"&linktarget=_self"+
				"&plugins=accessibility"+
				"&resizing=true"+
				"&stretching=none"+
				"&accessibility.hide=true"+
				"&accessibility.listener=captions_rundgang_main",
				"ep_video_teaser_main_r");
		showClickTour_r();
		
	}else if(element == 'e'){
		initFlashPlayer("/static/flash/player/player.swf", "flashplayerMain_erfolgsgeschichten", "445", "376",
				"debug=false"+
				"&controlbar=none"+
				"&skin=/static/flash/skins/playerSkin_startseite.swf"+
				"&autostart=true"+
				"&screencolor=#ffffff"+
				"&file=/static/flash/playlists/playlist-erfolgsgeschichten.xml"+
				"&icons=true"+
				"&linktarget=_self"+
				"&plugins=accessibility"+
				"&resizing=true"+
				"&stretching=none"+
				"&accessibility.hide=true"+
				"&accessibility.listener=captions_erfolgsgeschichten_main",
				"ep_video_teaser_main_e");
		showClickTour_e();
	}
	
}


/* Array mit den Links nach der Klicktour*/
var ClicktourLinks = new Array();
ClicktourLinks['w'] = EMN.WebappPrefix + '/registration/fregistrationpage.do';
ClicktourLinks['r'] = EMN.WebappPrefix + '/registration/fregistrationpage.do';
ClicktourLinks['e'] = EMN.WebappPrefix + '/erfolgsgeschichten/index.html';


var ClickTourNum = 0;

function moveClickTour(dir, type, count )
{
		
	var oldNum = ClickTourNum;
	if (dir == 'left')
	{ 
		 if (ClickTourNum > 0)
		 { 	
		 	ClickTourNum --;
		 	$("#clicktour_link_"+type).attr("href","#");
		 	$("#clicktour_link_"+type).each(function(){
		 	   this.onclick = function(){
		 		   		moveClickTour('right', type, count); 
		 		   		return false;
		 		   };
		 		});
		 	$("#clicktour_right_back_"+type).show();
		 	$("#clicktour_right_"+type).show();
		 }
		 if (ClickTourNum <= 0)
		 {
		 	$("#clicktour_left_"+type).hide();
		 	$("#clicktour_left_back_"+type).hide();
		 	$("#clicktour_right_"+type).hide();
		 	$("#clicktour_right_back_"+type).hide();
		 	$("#clicktour_link_"+type).show();
		 	
		 }
		 
	}
	else
	{
		if (ClickTourNum < count)
		 {
		 	
		 	ClickTourNum ++;
		 	
		 	$("#clicktour_left_"+type).show();
		 	$("#clicktour_left_back_"+type).show();
		 	$("#clicktour_right_back_"+type).show();
		 	$("#clicktour_right_"+type).show();
		 }
		 if (ClickTourNum == count)
		 {
		 	$("#clicktour_link_"+type).attr('href',ClicktourLinks[type]);
			$("#clicktour_link_"+type).removeAttr('onclick');
			$("#clicktour_right_"+type).hide();
		 	$("#clicktour_right_back_"+type).hide();
		 }
	}
	
	$('.ep_flashtext').hide();
	$('#ep_flash_text_'+type+ClickTourNum).show();

 	var src = $('#clicktour_img_'+type).attr('src');
	var new_src= src.replace(/[0-9]+/, ClickTourNum);
	
	$('#clicktour_img_'+type).attr('src', new_src);
}

function getRandomizedInterval(min, max) {
	return Math.round(min + ((max - min) * Math.random()));
}

/***************************************************** 
 *  Flashplayer Javascript Variables and Functions   *
 *****************************************************/

//global player var
var player;
// store the current player name because of a firefox bug
var currentPlayerName;
// array containing all names of flash videos, that should be tracked
var trackedFlashVideos=new Array("willkommen-main","rundgang-main","erfolgsgeschichten-main","landing1-main","landing2-main");

/*
 * Init Method for flashplayer object
 * 
 * @param playerPath the path to the player.swf
 * @param playerName the name for the player object
 * @param playerWidth the width of the player obect
 * @param playerHeight the heigth of the player object
 * @param flashvars a string containing all the flashvars for this player object
 * @param playerDiv the name of the div to write the player to
 */
function initFlashPlayer(playerPath, playerName, playerWidth, playerHeight, flashvars, playerDiv){
	var so = new SWFObject(playerPath, playerName, playerWidth, playerHeight, "9", "#FFFFFF");
	so.addParam("allowfullscreen","true");
	so.addParam("allowscriptaccess","always");
	so.addParam("wmode","transparent");
	so.addParam("flashvars",flashvars);
	so.setAttribute("name", playerName);
	so.setAttribute("id", playerName);
	so.write(playerDiv);
	
	// workaround firefox bug
	currentPlayerName = playerName;
};

/*
 * Registers listeners to the flashplayer
 * (Function is called automatically by the flashplayer)
 *
 */
function playerReady(obj){
	// workaround firefox bug
	if(obj.id == undefined){
		player = document.getElementsByName(currentPlayerName)[0];
	} else {
		player = document.getElementsByName(obj.id)[0];
	}	
	player.addControllerListener('ITEM','trackVideo');
	player.addModelListener('STATE', 'stateMonitor');
};

/*
 * Tracks all videos inserted into the array 'trackedFlashVideos'.
 * The method is triggered by the 'NEXT' event of the flashplayer and checks if
 * the next playlist entry should be tracked
 */
function trackVideo(){
	var currentItemTitle = player.getPlaylist()[player.getConfig().item].title;
	if(currentItemTitle != null){
		if(trackedFlashVideos.toString().indexOf(currentItemTitle) != -1){
			linkCode(player, currentItemTitle+"_video", 'shortHomepageRegistration');
		}
	}else{
		// tracking for magazin videos(no playlist yet)
		currentItemTitle = player.getPlaylist()[player.getConfig().item].file;
		if(currentItemTitle != null){
			if(currentItemTitle.lastIndexOf('_') != -1){
				currentItemTitle = currentItemTitle.substring(0,currentItemTitle.lastIndexOf('_'));
			}
			linkCode(player, currentItemTitle+"_video", 'magazin');
		}
	}
	
	// hack for not showing captions in "_end" films
	if(currentItemTitle.indexOf("-end") != -1){
		$(".ep_home_captions").css("visibility","hidden");
	}else{
		$(".ep_home_captions").css("visibility","visible");
	}
};
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;function uncheckCheckBox(box) {
	box.src = EMN.WebappPrefix + "/gfx/basic/icons/checkbox_off.gif";
}

function toggleCheckBoxImage(box) {
	if (box.src.indexOf('off.gif') != -1) {
		if (canSelectMore(box.id)) {
			box.src = EMN.WebappPrefix + '/gfx/basic/icons/checkbox_on.gif';
			incrementCounter(box.id);
			return true;
		} else {
			return false;
		}
	} else {
		box.src = EMN.WebappPrefix + '/gfx/basic/icons/checkbox_off.gif';
		decrementCounter(box.id);
		return false;
	}
}

function getBorderColor() {
	if (isNegativeContainer()) {
		return '#C60000';
	}

	return '#269100';
}

function handleGroupCheckBoxClick(event) {
	var box = event.target;
	var hiddenName = box.id.substring(0, box.id.lastIndexOf('_'));
	var hiddenValue = box.id.substring(box.id.lastIndexOf('_') + 1, box.id.length);

	toggleQuestionnaireCheckBox(hiddenName, box);
	
	$('#' + hiddenName).attr('value', hiddenValue);
}

function handleSimpleCheckBoxClick(event) {
	var box = event.target;
	
	var boxIsOn = toggleCheckBoxImage(box);
	
	var input = $('#' + box.id).prev();
	
	if (boxIsOn) {
		if ((input.attr('type') == 'radio') || (input.attr('type') == 'checkbox')) {
			input.attr('checked', 'checked');
		} else {
			input.attr('value', 1);
		}
	} else {
		if ((input.attr('type') == 'radio') || (input.attr('type') == 'checkbox')) {
			input.removeAttr('checked');
		} else {
			input.attr('value', 0);
		}
	}
}

var toggleQuestionnaireCheckBoxList = new Object();

function toggleQuestionnaireCheckBox(name, box) {
	if (toggleQuestionnaireCheckBoxList[name] != null) {
		uncheckCheckBox(toggleQuestionnaireCheckBoxList[name]);
	}
	
	toggleQuestionnaireCheckBoxList[name] = box;

	toggleCheckBoxImage(box);
}

function setGroupCheckBoxes() {
	list = new Array(
		"ep_q0090", "ep_q0110", "ep_q0100", "ep_q0280", "ep_q0290", "ep_q0210", "ep_q0220", "ep_q0230",
		"ep_q0300", "ep_q0310", "ep_q0320", "ep_q0330", "ep_q0340", "ep_q0350", "ep_q0360", "ep_q0370", "ep_q0380","ep_q0390",
		"ep_q0400", "ep_q0410", "ep_q0420", "ep_q0430", "ep_q0440", "ep_q0450", "ep_q0460", "ep_q0470", "ep_q0480","ep_q0490",
		"ep_q0500", "ep_q0510", "ep_q0520", "ep_q0530", "ep_q0540", "ep_q0550", "ep_q0560", "ep_q0570", "ep_q0580","ep_q0590",
		"ep_q0600", "ep_q0610", "ep_q0620", "ep_q0630", "ep_q0640", "ep_q0650", "ep_q0660", "ep_q0670", "ep_q0680","ep_q0690",
		"ep_q0700", "ep_q0710", "ep_q0720", "ep_q0730", "ep_q0740", "ep_q0750", "ep_q0760", "ep_q0770", "ep_q0780","ep_q0790",
		"ep_q0800", "ep_q0810", "ep_q0820", "ep_q0830", "ep_q0840", "ep_q0850", "ep_q0860", "ep_q0870", "ep_q0880","ep_q0890",
		"ep_q0900", "ep_q0910", "ep_q0920", "ep_q0930", "ep_q0940", "ep_q0950", "ep_q0960", "ep_q0970", "ep_q0980","ep_q0990",
		"ep_q0150boolean", "ep_q0150athome", "ep_q0160", "ep_geschlecht", "ep_sucheGeschlecht", "ep_q0120", "ep_q0130",
		"ep_q0050fish", "ep_q0050dogs", "ep_q0050cats", "ep_q0050birds", "ep_newsletter_choice"
	);
	
	for (var i=0; i<list.length; i++) {
		var elem = $('#' + list[i]);
		
		if (elem.length == 0) {
			continue;
		}

		$("img[id^='" + list[i] + "_']").bind('click', handleGroupCheckBoxClick);
		
		if (typeof(elem.attr('value')) == 'undefined' || elem.attr('value') == '') {
			elem.attr('value', -1);
		}
		
		if (elem.attr('value') != -1) {
			var id = elem.attr('value');
			var box = $('#' + list[i] + '_' + id).get(0);
			toggleQuestionnaireCheckBox(list[i], box);
		}
	}
}

function setSimpleCheckBoxes() {
	list = new Array(
		"qmagazines",
		"q0140",
		"q0240",
		"q0250",
		"q0260",
		"q0270",
		"qsavedata"
	);
	
	for (var i=0; i<list.length; i++) {
		var elem = $("input[name='" + list[i] + "']");
		if (elem.length == 0) {
			continue;
		}
		
		var box = elem.next();
		box.bind('click', handleSimpleCheckBoxClick);

		var elem = $("input[name='" + list[i] + "'][checked]");
		if (elem.length) {
			for (var j=0; j<elem.length; j++) {
				var box = elem.next().get(j);
				toggleCheckBoxImage(box);
			}
		}
	}
}

function setQuestionnaireLayers() {
	list = new Array(
		"qseasons",
		"q1000",
		"qliving",
		"q1010",
		"qfood",
		"qvacation"
	);

	registerClickLayer(list);
}

function initQuestionnaireTooltip() {	
	if ($('.ep_questionnaire_tool_icon').size() > 0) {		
			
			$('.ep_questionnaire_tool_icon').tooltip({	
		    	bodyHandler: function() {
				switch ($(this).attr("longdesc")) {
					case '5':
						return "<h3>trifft &uuml;berhaupt nicht zu</h3>";
						break;
					case '4':
						return "<h3>trifft eher nicht zu</h3>";
						break;
					case '3':
						return "<h3>trifft weniger zu</h3>";
						break;
					case '2':
						return "<h3>trifft einigerma&szlig;en zu</h3>";
						break;
					case '1':
						return "<h3>trifft &uuml;berwiegend zu</h3>";
						break;
					case '0':
						return "<h3>trifft vollkommen zu</h3>";
						break;
					}
  				}, 			
				track: true, 
			    delay: 0, 
			    showURL: false, 
			    opacity: 1, 
			    fixPNG: true, 
			    
			    extraClass: "ep_questionnaire_tooltip"			    
			});
		}
}

$(document).ready(function() {
 	initQuestionnaireTooltip();
 	initQuestionnaireHover();
 	setQuestionnaireLayers();
	setGroupCheckBoxes();
	setSimpleCheckBoxes();
});
function printWindow(){
   bversion = parseInt(navigator.appVersion)
   if (bversion >= 4) window.print()
}

function submitFormAndDisableElement (styleId, element){
	element.disabled = true;
	form = document.getElementById(styleId);
	form.submit();	
}

function submitTwoButtonForm (styleId, value){
	form = document.getElementById(styleId);
	form.button_value.value=value;
	form.submit();	
}

function submitManyButtonForm (styleId, value){
	form = document.getElementById(styleId);
	for (var i=0; i<form.product_id.length; i++) {
	  if (form.product_id[i].value == value) {
	    form.product_id[i].checked = true;
	  }
	}
	form.submit();	
}

function submitClickForm (event,styleId){
	if (event.keyCode == 13) {
		form = document.getElementById(styleId);
		form.submit();	
  } else {
   return true;
  }
}

function submitPhoto (styleId, slot){
	form = document.getElementById(styleId);
	if (slot == "save0") {
		form.save0.value = "true";
	} else 	if (slot == "save1") {
		form.save1.value = "true";
	} else 	if (slot == "save2") {
		form.save2.value = "true";
	}
	form.submit();	
}
function submitUpdatePData (styleId, pdata){
	form = document.getElementById(styleId);
	if (pdata == "alias") {
		form.actalias.value = "true";
	} else 	if (pdata == "rating") {
		form.actrating.value = "true";
	}
	form.submit();	
}


function saveRating(chiffre, selectionStyleId, iframeStyleId) {
	var selection = document.getElementById(selectionStyleId);
	var rating = null;
	
	for (var i = 0; i < selection.length; ++i){
    if (selection.options[i].selected == true){
      rating = selection.options[i].value;
		}			
	}		
	if (chiffre != null && rating != null){
		new Ajax.Request(
			EMN.WebappPrefix + '/members/profiles/updateProfileRating.do',
			{ method:'post', parameters: {chiffre: chiffre, rating: rating}}
		);
	}	
}


function disableButton(fobject) {
	fobject.disabled = true;
	fobject.form.submit();
}

function switchMainWin(url) {
 win = open(url,"mainwin");
 win.focus(); 
}

function openPopup(url) {
	popwin = window.open(EMN.WebappPrefix + url +'','Popup','width=500,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (popwin.mainwin == null) popwin.mainwin = self;
	popwin.focus();
}
function openPopup(url,h,w) {
	var x = screen.width/2 - w/2;
	var y = screen.height/2 -h/2
	popwin = window.open(EMN.WebappPrefix + url+'','Popup','width='+w+',height='+h+',top='+y+',left='+x+',scrollbars=no,status=no,toolbar=no,resizable=no,location=no');
	if (popwin.mainwin == null) popwin.mainwin = self;
	popwin.focus();
}

function openTest() {
	tstwin = window.open(EMN.WebappPrefix + '/members/q/q1/qStart.do','Popup','width=765,height=610,top=0,left=0,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (tstwin.mainwin == null) tstwin.mainwin = self;
	tstwin.focus();
}

function openAGB() {
	agbwin = window.open(EMN.WebappPrefix + '/agb.do','AGBPopup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (agbwin.mainwin == null) agbwin.mainwin = self;
	agbwin.focus();
}

function openEventAGB() {
	agbwin = window.open(EMN.WebappPrefix + '/service/event/agb.do','EventAGBPopup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (agbwin.mainwin == null) agbwin.mainwin = self;
	agbwin.focus();
}

function openAGBVerhaltensverpflichtungen() {
	agbwin = window.open(EMN.WebappPrefix + '/agb.do#verhaltensverpflichtungen','AGBPopup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (agbwin.mainwin == null) agbwin.mainwin = self;
	agbwin.focus();
}

function openPrivacyTerms() {
	privacywin = window.open(EMN.WebappPrefix + '/datenschutz.do','PrivacyTermsPopup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (privacywin.mainwin == null) privacywin.mainwin = self;
	privacywin.focus();
}

function openLotteryParticipationConditions(adId, pg) {
	var baseUrl = EMN.WebappPrefix + '/aktionen/lotteryConditions.do';
	var url = baseUrl + "?ad_id=" + adId + "&pg=" + pg; 
	win = window.open(url,'LotteryPopup','width=500,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (win.mainwin == null) win.mainwin = self;
	win.focus();
}

function openFriendshipPortraitConditions() {
	var url = EMN.WebappPrefix + '/friendship/friendshipPortraitConditions.do';
	win = window.open(url,'Popup','width=600,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (win.mainwin == null) win.mainwin = self;
	win.focus();
}

function openFriendshipPortraitPhotoConditions() {
	var url = EMN.WebappPrefix + '/friendship/friendshipPortraitPhotoConditions.do';
	win = window.open(url,'Popup','width=600,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (win.mainwin == null) win.mainwin = self;
	win.focus();
}

function openOthersAboutMeExample() {
	var url = EMN.WebappPrefix + '/members/settings/othersAboutMeExample.do';
	win = window.open(url,'Popup','width=709,height=360,top=50,left=50,scrollbars=no,status=no,toolbar=no,resizable=no,location=no');
	if (win.mainwin == null) win.mainwin = self;
	win.focus();
}

function openProductInfo(product, index, voucherCode) {
	var evc = voucherCode && voucherCode != '' ? '&effective_voucher_id='+voucherCode : '';
	productinfowin = window.open(EMN.WebappPrefix + '/preise_und_leistungen/info.do?product='+product+'&index='+index+evc+'','Popup','width=500,height=550,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (productinfowin.mainwin == null) productinfowin.mainwin = self;
	productinfowin.focus();
}

function openProductInfoWithoutCheck(product, date, domain, voucherCode) {
	var evc = voucherCode ? '&effective_voucher_id='+voucherCode : '';
	productinfowin = window.open(EMN.WebappPrefix + '/preise_und_leistungen/info.do?product='+product+'&check=false&date='+date+'&domain='+domain+evc,'Popup','width=500,height=550,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (productinfowin.mainwin == null) productinfowin.mainwin = self;
	productinfowin.focus();
}


function openHelp() {
	helpwin = window.open(EMN.WebappPrefix + '/hilfe/index.do','Popup','width=800,height=600,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (helpwin.mainwin == null) helpwin.mainwin = self;
	helpwin.focus();
}

function openTestHelp() {
	helpwin = window.open(EMN.WebappPrefix + '/hilfe/test_help.do','Popup','width=520,height=300,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (helpwin.mainwin == null) helpwin.mainwin = self;
	helpwin.focus();
}

function openSecurePasswordHelp() {
	helpwin = window.open(EMN.WebappPrefix + '/hilfe/securePassword.do','Popup','width=520,height=450,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (helpwin.mainwin == null) helpwin.mainwin = self;
	helpwin.focus();
}

function openProfileHeadPopup(peerChiffre, headTileLocation) {
	var baseUrl = EMN.WebappPrefix + '/members/profiles/profileHeadPopup.do';
	var url = baseUrl + "?chiffre=" + peerChiffre + "&location=" + headTileLocation; 
	var helpwin = window.open(url,'Popup','width=460,height=350,top=70,left=200,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (helpwin.mainwin == null) helpwin.mainwin = self;
	helpwin.focus();
}

function openEliteBlog() {
	var url = 'http://www.EliteBlog.de';
	var win = window.open(url,'EliteBlog','width=700,height=500,top=50,left=50,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (win.mainwin == null) helpwin.mainwin = self;
	win.focus();
}

function openSuccessIndexHelp() {
	var successIndexWin = window.open(EMN.WebappPrefix + '/members/successIndexPopup.do','Popup','width=500,height=380,top=50,left=150,scrollbars=no,status=no,toolbar=no,resizable=no,location=no');
	if (successIndexWin.mainwin == null) successIndexWin.mainwin = self;
	successIndexWin.focus();
}

function leftTeaserLink() { 
	window.location.href = EMN.WebappPrefix + '/service/beratung/index.jsp';
}

/*opens a popup with explanation about "dufttyp A"*/
function openDA() {
	dwin = window.open(EMN.WebappPrefix + '/misc/dufttypA.do','Popup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (dwin.mainwin == null) dwin.mainwin = self;
	dwin.focus();
}

/*opens a popup with explanation about "dufttyp B"*/
function openDB() {
	dwin = window.open(EMN.WebappPrefix + '/misc/dufttypB.do','Popup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (dwin.mainwin == null) dwin.mainwin = self;
	dwin.focus();
}

function openSD(ttarget) {
	ppswin = window.open(EMN.WebappPrefix + '/misc/ppscales.do#'+ttarget,'Popup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (ppswin.mainwin == null) ppswin.mainwin = self;
	ppswin.focus();
}

function closePopup() {
	if (window.mainwin != null) {
		window.mainwin.focus();
	}
	window.close();
	window.mainwin.location.reload();
}

function closePopupWithoutReload() {
  window.close();
  opener.focus();
}

function openGallery(url) {
	popup = window.open(url,'Popup','width=710,height=550,top=50,left=20,scrollbars=auto,status=no,toolbar=no,resizable=yes,location=no');
	if (popup.mainwin == null) popup.mainwin = self;
	popup.focus();
}

function changeCountry (form) {
	form.act.value = "reload";
	form.submit();
}


function openDA() {
	dwin = window.open(EMN.WebappPrefix + '/misc/dufttypA.do','Popup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (dwin.mainwin == null) dwin.mainwin = self;
	dwin.focus();
}

function openDB() {
	dwin = window.open(EMN.WebappPrefix + '/misc/dufttypB.do','Popup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (dwin.mainwin == null) dwin.mainwin = self;
	dwin.focus();
}

function openSD(ttarget) {
	ppswin = window.open(EMN.WebappPrefix + '/misc/ppscales.do#'+ttarget,'Popup','width=520,height=500,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (ppswin.mainwin == null) ppswin.mainwin = self;
	ppswin.focus();
}

function closePopup() {
	if (window.mainwin != null) {
		window.mainwin.focus();
	}
	window.close();
	window.mainwin.location.reload();
}

function openGallery(url) {
	popup = window.open(url,'Popup','width=710,height=550,top=50,left=20,scrollbars=auto,status=no,toolbar=no,resizable=yes,location=no');
	if (popup.mainwin == null) popup.mainwin = self;
	popup.focus();
}

function changeCountry (form) {
	form.act.value = "reload";
	form.submit();
}

function onClickSelectDefault(field, defaultValue) {
 if (field.value == defaultValue) {
   field.select();
 }
}

function readProductInfo(product, index) {
  var infoChecks = opener.getFormProperty('pForm', 'info_check');
  if(infoChecks.length > 1){
	  for (var i=0; i<infoChecks.length; i++) {
	    if (infoChecks[i].value == product) {
		    opener.setFormPropertyChecked('pForm', 'info_check', i, true);
	    }
	  }
  }else{
	  opener.setFormPropertyVIP('pForm', 'info_check', true);
  }
  var products = opener.getFormProperty('pForm', 'product_id');
  for (i=0; i<products.length; i++) {
    if (products[i].value == product) {
	    opener.setFormPropertyChecked('pForm', 'product_id', i, true);
    }
  }
  
  window.close();
  opener.focus();
  opener.submitFormByName('pForm');
}

function setFormPropertyVIP(formName, propertyName, propertyValue){
  document.forms[formName].elements[propertyName].checked = propertyValue;
}

function setFormProperty(formName, propertyName, propertyValue) {
  document.forms[formName].elements[propertyName].value = propertyValue;
}

function setFormPropertyChecked(formName, propertyName, index, checked) {
  document.forms[formName].elements[propertyName][index].checked = checked;
}

function getFormProperty(formName, propertyName) {
  return document.forms[formName].elements[propertyName];
}

function submitFormByName(formName) {
  document.forms[formName].submit();
}


function readVoucherProductInfo(effectiveVoucherId,campaignName){
  
  window.close();
  opener.focus();
  url = EMN.WebappPrefix + '/ppreise_und_leistungen.do'
  url = url + '?effective_voucher_id='+effectiveVoucherId + '&campaignName='+campaignName+'&info_check='+effectiveVoucherId;
  opener.location.href=url;
}

// Call on costs benefits page if product has been changed
function changedProduct(formId, productId, action) {
  if (productId != lastSelectedProduct) {
    lastSelectedProduct=productId;
	  form = document.getElementById(formId);
  	form.action=action;
	  form.submit();
	}
}

function openProductInfoWithChangedProduct(formId, product, action, index) {
  form = document.getElementById(formId);
  var products = form.elements['product_id'];
  for (var i=0;i<products.length;i++) {
    if (products[i].value == product) {
      products[i].checked = true;
    }
  }
  
	productinfowin = window.open(EMN.WebappPrefix + '/preise_und_leistungen/info.do?product='+product+'&index='+index+'','Popup','width=500,height=550,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
	if (productinfowin.mainwin == null) productinfowin.mainwin = self;
	productinfowin.focus();
	
	changedProduct(formId, product, action);
}

// Selection of voucher that has a special tied product makes it
// necessary that the voucher id is stored into hidden field 'effective_voucher_id'.
function submitTiedToVoucherProduct (formId, effectiveVoucherId) {
  form = document.getElementById(formId);
  form.elements['effective_voucher_id'].value = effectiveVoucherId;
  form.elements['info_check'].value = effectiveVoucherId;
  form.submit();
}

function openVoucherInfoPopup(effectiveVoucherCode, isTiedToProduct) {
  if (!isTiedToProduct) {
	  voucherinfowin = window.open(EMN.WebappPrefix + '/preise_und_leistungen/voucherInfoWithoutProduct.do?evc='+effectiveVoucherCode+'','Popup','width=500,height=550,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
    voucherinfowin.focus();
	} else {
	  alert('currently not possible');
	}

}

// Shows a popup window with informations about the product
function openProductVoucherInfoPopup(effectiveVoucherCode) {
  voucherinfowin = window.open(EMN.WebappPrefix + '/preise_und_leistungen/voucherInfoWithProduct.do?effective_voucher_id='+effectiveVoucherCode+'','Popup','width=500,height=550,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
  voucherinfowin.focus();
}

// Shows same popup as openProductVoucherInfoPopup but provides only a close button
function openProductVoucherInfoPopupWithoutCheck(effectiveVoucherCode, date) {
  voucherinfowin = window.open(EMN.WebappPrefix + '/preise_und_leistungen/voucherInfoWithProduct.do?check=false&effective_voucher_id='+effectiveVoucherCode+'&date='+date,'Popup','width=500,height=550,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
  voucherinfowin.focus();
}

function openCMSLink(url) {
		cmsLinkwin = window.open(url,'CMSLink','width=590,height=700,top=50,left=150,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no');
		if (cmsLinkwin.mainwin == null) cmsLinkwin.mainwin = self;
		cmsLinkwin.focus();
}

function saveAliasAndMemo(peerChiffre, alias, memo, oldAlias, oldMemo) {
	if(!alias) {
		alias = '';
	}
	if(!memo) {
		memo = '';
	}
	if(!oldAlias) {
		oldAlias = '';
	}
	if(!oldMemo) {
		oldMemo = '';
	}
	new Ajax.Request(
		EMN.WebappPrefix + '/members/profiles/profileHeadPopupUpdateContact.do',
		{
			method:'post', parameters: {chiffre: peerChiffre, aliasOrChiffre: alias, memo: memo, oldAliasOrChiffre: oldAlias, oldMemo: oldMemo},
			onSuccess: function(transport){
		    	location.reload();
		    }	
		}
	);
}

function saveRating(chiffre, selectionStyleId, iframeStyleId) {
	var selection = document.getElementById(selectionStyleId);
	var rating = null;
	
	for (var i = 0; i < selection.length; ++i){
    if (selection.options[i].selected == true){
      rating = selection.options[i].value;
		}			
	}		
	if (chiffre != null && rating != null){
		new Ajax.Request(
			EMN.WebappPrefix + '/members/profiles/updateProfileRating.do',
			{ method:'post', parameters: {chiffre: chiffre, rating: rating}}
		);	
	}	
}


/******* Social Bookmarking functions ******/
/**
* toggles SocialBookmark-Box on and off
* @param spDisplay - ture=on, false=off
*/
function SocialBookmarkSetDisplay(spDisplay) {
SocialBookmarkElement = document.getElementById("SocialBookmark").style;
SocialBookmarkElement.visibility = (spDisplay ? "visible" : "hidden");
SocialBookmarkState=spDisplay;
}
/**
* toggle function called form Bookmark Link
* served SocialBookmarkSetDisplay() and starts EventHandler
*/
function SocialBookmarkToggle() {
if (!SocialBookmarkState) {
SocialBookmarkSetDisplay(true);
spStartMouseEvent();
}
else 
SocialBookmarkSetDisplay(false);
}
/**
* Event handler function tests where the user clicked
* and acts	according to this (switch SocialBookmark-Box off 
* stops EventHandler)
*/
function SocialBookmarkToggleDisplay(e) {
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
if (targ.id == "SocialBookmarkLink") {
spStopMouseEvent();
return false;
}
var isInDiv = false;
while(targ != null) {
if (targ.id == "SocialBookmark") {
isInDiv=true;
break;
}
if (targ.id == "SocialBookmarkClose")
break;
targ = targ.parentNode;
}
if (!isInDiv) {
SocialBookmarkSetDisplay(false);
spStopMouseEvent();
}
return false;
}
/**
* starts EventHandling
*/
function spStartMouseEvent(){
if (document.addEventListener) { // DOM Level 2 Event Model
document.addEventListener("mouseup", SocialBookmarkToggleDisplay, true);
}
else if (document.attachEvent) { // IE 5+ Event Model
document.attachEvent("onmouseup", SocialBookmarkToggleDisplay);
}
else { // IE 4 Event Model
document.onmouseup=SocialBookmarkToggleDisplay;
}
}
/**
* stops EventHandling
* spOldHandler is a hack for EI4 Event Model
*/
var spOldHandler = document.onmouseup;	// Eventhandler for EI 4 StopEvent
function spStopMouseEvent() {
// Unregister the capturing event handlers.
if (document.removeEventListener) { // DOM Event Model
document.removeEventListener("mouseup", SocialBookmarkToggleDisplay, true);
}
else if (document.detachEvent) { // IE 5+ Event Model
document.detachEvent("onmouseup", SocialBookmarkToggleDisplay);
}
else { // IE 4 Event Model
document.onmouseup = spOldHandler;
}
}
function spInArray(haystack, needle) {
for (var i in haystack) {
if (haystack[i] == needle)
return true;
}
return false;
}

/* toggles display value: 'block' -> 'none' -> 'block' */
function toggleById(id) {
	var el = document.getElementById(id);
	/*alert(el.style.display);*/
	if ( el.style.display != 'block' ) {
		el.style.display = 'block';
	}
	else {
		el.style.display = 'none';
	}
}

function getURLParam(strParamName){
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ) {
		var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
			if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ) {
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return strReturn;
}


/**
 * Sets onclick event for element starting with "name_". Sets value of corresponding hidden element to -1
 * if it is not set.
 */
function registerCheckBox(name) {
	var elem = $('#' + name);
	
	$("[id^='" + name + "_']").bind('click', handleCheckBoxClick);
	
	// set value of corresponding hidden element to -1 if it is not set
	if (typeof(elem.attr('value')) == 'undefined' || elem.attr('value') == '') {
		elem.attr('value', -1);
	}
}
/**
 * Event handler for clicked check boxes. Sets value of corresponding hidden field by given id of checkbox.
 * 
 * A check box with id="ep_gender_0" sets the element (hopefully a hidden
 * element) with id="ep_gender" to "0".
 * 
 */
function handleCheckBoxClick(event) {
	var box = event.target;
	
	var hiddenName = box.id.substring(0, box.id.lastIndexOf('_'));
	var hiddenValue = box.id.substring(box.id.lastIndexOf('_') + 1, box.id.length);
	
	toggleCheckBox(hiddenName, box);
	$('#' + hiddenName).attr('value', hiddenValue);
}

// global variable that holds list of clicked check boxes, belongs to toggleCheckBox()
var _toggleCheckBoxList = new Object();

/**
 * Toggles images of check boxes.
 */
function toggleCheckBox(name, box) {
	if (_toggleCheckBoxList[name] != null) {
		_toggleCheckBoxList[name].src = EMN.WebappPrefix + '/gfx/basic/icons/checkbox_off.gif';
	}
	
	_toggleCheckBoxList[name] = box;

	if (box.src.indexOf('off.gif') != -1) {
		box.src = EMN.WebappPrefix + '/gfx/basic/icons/checkbox_on.gif';
	} else {
		box.src = EMN.WebappPrefix + '/gfx/basic/icons/checkbox_off.gif';
	}
}


/**
 * Disables further checkboxes when max number of allowed checkboxes are checked
 */
function maxRadios(max,box,formStyleClass){
	var checked='.' + formStyleClass+" input:checked";
	if($(checked).length>max){
		box.checked = false;
	}	
} 


/**
 * opens a popup where the user can upload, delete and swap photos
 */
function openPhotoPage() {
	var phototool = window.open(EMN.WebappPrefix + "/members/settings/fphotos.do", "Phototool", "width=870, height=940, resizable=yes , scrollbars=yes");
	phototool.focus();
}

/**
 * opens a popup to display a photo
 */
function openOriginalPhoto(chiffre, slot) {
	var photo = window.open(EMN.WebappPrefix + "/members/profiles/photo.do?chiffre=" + chiffre + "&slot=" + slot, "", "width=820, height=1020, resizable=yes , scrollbars=no");
	photo.focus();
}

/**
 * opens a popup where the user can see the original pictures
 */
function openGalleryPage(chiffre, slot) {
	var gallery = window.open(EMN.WebappPrefix + "/members/profiles/gallery.do?chiffre="+chiffre+"&slot="+slot, "gallery", "width=750,height=900,top=50,left=20,scrollbars=yes,status=no,toolbar=no,resizable=yes,location=no");
	gallery.focus();
}

/**
 * opens a popup where the user can upload, delete and swap photos
 */
function openPhotoPageInfo() {
	var photoInfo = window.open(EMN.WebappPrefix + "/misc/photosInfo.do", "Photoinfo", "width=705, height=750, resizable=yes , scrollbars=yes");
	photoInfo.focus();
}

/**
 * hover function of thumbnails in profile. if you hover over the thumbnails the mainpic will be replaced
 */
function showMainPhotoOfSlot(slot, count){
	for (var i = 0; i < count; i++) {
        if (i == slot) {
            $('#ep_slot' + i).css('display', 'block');
            $('#ep_small_pic' + i).addClass("ep_photo_selected");;
        } else {
            $('#ep_slot' + i).hide();
            $('#ep_small_pic' + i).removeClass("ep_photo_selected");;
        }
    }
}

/**
 * changes pictures to scrambled and back in /settings/view/profile.do, also a corresponding infotext will be displayed
 */
var Picview = 0
function tooglePicview() {
	if(Picview == 0){ //photos are not scrambeld and should be scrambled
		$('#ep_profile_mainpic img').each(function (i) {		
			var src = $(this).attr('src');
			var new_src= src.replace("tid=2","tid=3");
			$(this).attr('src', new_src);
		});

		$('.ep_small_pic img').each(function (i) {		
			var src = $(this).attr('src');
			var new_src= src.replace("tid=4","tid=3");
			$(this).attr('src', new_src);
		});

		//show text for scrambled
		$('#ep_infotext_picview_current_scrambled_true').show();
		$('#ep_text_changephoto_view_current_scrambled_true').show();
		
		//hide text for unscrambled
		$('#ep_infotext_picview_current_scrambled_false').hide();
		$('#ep_text_changephoto_view_current_scrambled_false').hide();
		Picview = 1;
		
	} else { //photos are scrambeld and should NOT be scrambled
		$('#ep_profile_mainpic img').each(function (i) {		
			var src = $(this).attr('src');
			var new_src= src.replace("tid=3","tid=2");
			$(this).attr('src', new_src);
		});

		$('.ep_small_pic img').each(function (i) {		
			var src = $(this).attr('src');
			var new_src= src.replace("tid=3","tid=4");
			$(this).attr('src', new_src);
		});
		
		//hide text for scrambled
		$('#ep_infotext_picview_current_scrambled_true').hide();
		$('#ep_text_changephoto_view_current_scrambled_true').hide();
		
		//show text for unscrambled
		$('#ep_infotext_picview_current_scrambled_false').show();
		$('#ep_text_changephoto_view_current_scrambled_false').show();
		Picview = 0;	
	}
}

/**
 * Returns true if the user can select more click layers. Works with elements' content (preferrably <span id="ep_...">...</span>).
 */
function canSelectMore(name) {
	var elemChosen = $('#ep_choose_count');
	var elemMax = $('#ep_max_number');
	
	if ((elemChosen.length != 0) && (elemMax.length != 0)) {
		// use default elements
		return (elemChosen.html() < elemMax.html());
	}
	
	// if default elements are not present, use custom ones
	var prefix = name.substring(0, name.lastIndexOf('_'));
	chosenName = '#' + prefix + '_choose_count';
	maxName = '#' + prefix + '_max_number';
	
	elemChosen = $(chosenName);
	elemMax = $(maxName);
	
	if ((elemChosen.length == 0) && (elemMax.length == 0)) {
		// allow selecting more if elements can not be found
		return true;
	}
	
	return (elemChosen.html() < elemMax.html());
}

/**
 * Increments the counter, that is queried by canSelectMore()
 */
function incrementCounter(name) {
	var elem = $('#ep_choose_count');
	
	if (elem.length) {
		// use default element
		var count = elem.html();
		count++;
		elem.html(count);
		
		return;
	}
	
	// if default element is not present, use custom one
	var prefix = name.substring(0, name.lastIndexOf('_'));
	var chosenName = '#' + prefix + '_choose_count';
	
	elem = $(chosenName);
	
	if (elem.length) {
		var count = elem.html();
		count++;
		elem.html(count);
	}
}

/**
 * Decrements the counter, that is queried by canSelectMore()
 */
function decrementCounter(name) {
	var elem = $('#ep_choose_count');
	
	if (elem.length) {
		// use default element
		var count = elem.html();
		if (count > 0) {
			if (count == 1) {
				count = '0';
			} else {
				count--;
			}
		}
		elem.html(count);
		
		return;
	}
	
	// if default element is not present, use custom one
	var prefix = name.substring(0, name.lastIndexOf('_'));
	var chosenName = '#' + prefix + '_choose_count';
	
	elem = $(chosenName);
	
	if (elem.length) {
		var count = elem.html();
		if (count > 0) {
			if (count == 1) {
				count = '0';
			} else {
				count--;
			}
		}
		elem.html(count);
	}
}

/**
 * Returns true if negative container exists.
 */
function isNegativeContainer() {
	return ($('.ep_negative_choose').size() > 0);
}

/**
 * Sets tooltip for a given elem.
 */
function setTooltip(elem) {
	if (isNegativeContainer()) {
		elem.tooltip({
			track: true,
			delay: 0,
			showURL: false,
			opacity: 1,
			fixPNG: true,
			top: 10,
			left: 5,
			extraClass: "ep_tooltip_neg"
		});
	} else {
		elem.tooltip({
			track: true,
			delay: 0,
			showURL: false,
			opacity: 1,
			fixPNG: true,
			top: 10,
			left: 5,
			extraClass: "ep_tooltip"
		});
	}
}

/**
 * Callback function for a selected click layer.
 */
function selectTestLayer(layer) {
	var color = getBorderColor();
	
	layer.attr('class', 'ep_test_layer ep_active');
	layer.css('border','5px solid ' + color);
	layer.css('height', layer.height() - 4);

	var imgElem = layer.children('img'); 
	imgElem.attr('title', 'abwählen');
	setTooltip(imgElem);
	
	var head = layer.prev().prev().prev().prev();
	head.css('color', '#269100');
}

/**
 * Callback function for a deselected click layer.
 */
function deselectTestLayer(layer) {
	var color = getBorderColor();
	
	layer.attr('class', 'ep_test_layer');
	layer.css('border','3px solid '+ color);
	
	var height= layer.height();
	height = height+4;
	layer.height(height);
	
	var imgElem = layer.children('img'); 
	imgElem.attr('title', 'auswählen');
	setTooltip(imgElem);
	
	var head= layer.prev().prev().prev().prev();
	$(head).css('color', '#534F48');
}

/**
 * Selects given test layers, i.e. highlight them.
 */
function registerClickLayer(elems) {
	if (typeof(elems) == "string") {
		elems = new Array(elems);
	}
	
	for (i=0; i<elems.length; i++) {
		var elem = $("input[name='" + elems[i] + "'][checked]").next().next();
		
		if (elem.length == 0) {
			continue;
		}
		
		elem.each(function() {
			selectTestLayer($(this));
		});
		
		for (var j=0; j<elem.length; j++) {
			incrementCounter();
		}
	}
}

/**
 * Highlights existing click layers and set handlers for onHover and onClick.
 */
function initQuestionnaireHover() {
	var borderColor = getBorderColor();

	if ($('.ep_choosen_layer').size() > 0) {
		// already chosen layers
		$('.ep_choosen_layer').each(function() {
			var height = $(this).parent().height();
			height = height-4;
			var imgHeight = height-10;

			$(this).css('height', height);

			$('#' + this.id +' img').css('height', imgHeight);
		});
	}

	if ($('.ep_test_layer').size() > 0) {
		// layers with hover functionality
		$('.ep_test_layer').each(function() {
			var height = $(this).parent().height();
			var imgHeight = height-6;
			$(this).css('height', height);

			$('#' + this.id + ' img').css('height', imgHeight);
		});

		$('.ep_test_layer').hover(function() {
			if ($(this).attr('class') == 'ep_test_layer ep_active') {
				$(this).css('border', '5px solid ' + borderColor);
			} else {
				$(this).css('border', '3px solid ' + borderColor);
			}
		}, function() {
			if ($(this).attr('class') == 'ep_test_layer ep_active') {
			} else {
				$(this).css('border','3px transparent');
			}
		});

		$('.ep_test_layer').click(function() {
			if ($(this).attr('class') == 'ep_test_layer') {
				if (canSelectMore()) {
					selectTestLayer($(this));

					var input = $(this).prev().prev();
				
					if (($(input).attr('type') == 'radio') || ($(input).attr('type') == 'checkbox')) {
						$(input).attr('checked', 'checked');
					} else {
						$(input).attr('value', 1);
					}
					
					incrementCounter();
				}
			} else {
				deselectTestLayer($(this));

				var input = $(this).prev().prev();
				if (($(input).attr('type') == 'radio') || ($(input).attr('type') == 'checkbox')) {
					$(input).removeAttr('checked');
				} else {
					$(input).attr('value', 0);
				}
				
				decrementCounter();
			}
		});
	}
}

/**
* Adds or removes a favorite
*/
function addOrRemoveFavorite(type, imageId, peerChiffre){
  
  $.post(EMN.WebappPrefix + "/members/contacting/favorite.do", {type: type, imageId: imageId, peerChiffreForFavorite: peerChiffre},
  function(data){
  	var replaceElement = $('#favorite' + imageId);
    replaceContentOrHandleTimeout(replaceElement,data);
  });
  
}

/**
* Replaces the content of the replaceElement with the provided 
* response data or sends the User to the login page
*/
function replaceContentOrHandleTimeout(replaceElement,response){
		if (!isSessionTimeout(response)){
		  replaceElement.html(response);
		}else{
			document.location.href=EMN.WebappPrefix + '/flogin.do';
		}
}

/**
* Returns true if an ajax session timeout occured
*/
function isSessionTimeout(response){
 return response == 'AJAX-SESSION-TIME-OUT';
}

/** 
* switch for profilHead and shortProfileHead
*/
function toggleProfileHead () {
	if ($("#ep_profile_head").hasClass("ep_dn")) {
		hideElement ("ep_short_profile_head");
		displayElement ("ep_profile_head");
	} else {
		hideElement ("ep_profile_head");
		displayElement ("ep_short_profile_head");
	}
	return false;
}

/**
* Shows the element with given id
*/
function displayElement (id) {
	$("#" + id).removeClass("ep_dn");
	return false;
}

/**
* Hides the element with the given id
*/
function hideElement (id) {
	$("#" + id).addClass("ep_dn");
	return false;
}

/**
* Sets the fontsize of the page
*/
function setFontsize (size, id, oids) {
	$.post(EMN.WebappPrefix + "/misc/setFontsize.do", {fontsize: size},
	function(data){
		$("#" + id).addClass("ep_active");
		for (var i = 0; i < oids.length; i++) {
			$("#" + oids[i]).removeClass("ep_active");
		}
		$("#ep_body").attr("style","font-size:" + size + "%;");
	});
	return false;
}

/**
* Bookmarks the provided site with the given parameters 
*/
function bookmarkMe(url, key1, key2) {
	window.open(url + (key1 != null ? "&" + key1 + "=" + encodeURIComponent(location.href) : "") + (key2 != null ? "&" + key2 + "=" + encodeURIComponent(document.title) : ""));
	return false;
}

// overrides function in main_functions.js TODOJS Replace code in main_functions.js with this version.
function magazinLayerHeight()
{
	if ($('.ep_magazin_layer').size() > 0)
	{
		$('.ep_magazin_layer').each(function()
			{
			var height= $(this).parent().height();
			
			$(this).css('height', height);
			
			$(this).children('a').children('img').css('height',height);

			}
		);
	}


}

/**
  *	hides images behind the tooltip to avoid display problems in damn IE
  * TODO MH method will become obsolete when tooltip problems are solved
  */
 function hideImagesProfileCompare(){
 	if($.browser.msie){
 		$('.ep_compare_image_container_0').attr("style","visibility:hidden");
 	}
 }
 
 /**
  *	shows previously hidden images behind the tooltip to avoid display problems in damn IE
  * TODO MH method will become obsolete when tooltip problems are solved
  */
 function showImagesProfileCompare(){
 	if($.browser.msie){
 		$('.ep_compare_image_container_0').attr("style","visibility:visible");
 		
 	}
 }

/*
 * Toggles teaser elements
 * param elementId = teaser elementId, 
 * param title = teaser title
 * param open = open text
 * param close = close text
 *
 * TODO MH this method makes method toggleTeaserContent in main_functions.js obsolete!
 */
function toggleTeaser(elementId, title, open, close)
{
	if($('#'+elementId+'_arrow').attr('src').indexOf('arrow_close.gif')!=-1)
	{
		$('#'+elementId+'_arrow').attr("title",title + " " + open);
		$('#'+elementId+'_arrow').attr('src', EMN.WebappPrefix + "/gfx/basic/icons/arrow_open.gif");
		if($.browser.msie && $.browser.version <= 6)
		{
			$('#'+elementId+'_content').hide();
		}
		else
		{
		$('#'+elementId+'_content').animate(
            {
                height: 'toggle'
            }
            );
        }	
	}
	else{
		$('#'+elementId+'_arrow').attr("title",title + " " + close);
		$('#'+elementId+'_arrow').attr('src', EMN.WebappPrefix + "/gfx/basic/icons/arrow_close.gif");	
		
		if($.browser.msie && $.browser.version <= 6)
		{
			$('#'+elementId+'_content').show();
		}
		else
		{
			$('#'+elementId+'_content').animate(
            {
                height: 'toggle'
            }
            );
        }
	}
} 

// Open/close additional data in basic data of a member
function toggleAdditionalData()
{		
	if ($('#additionalData').css('display') == 'none' )
	{	
		$('#additionalData').show();
		$('#additionalDataLink').html('Zusatzdaten ausblenden');
	}
	else
	{
		$('#additionalData').hide();
		$('#additionalDataLink').html('Zusatzdaten einblenden');
	}
}

function toggle_send_welcome_questions_text(){
	var sendQuestions=$("#ep_cb_send_questions_text").attr("checked");
	$("#ep_send_questions").attr("checked", sendQuestions);
	$("#ep_dont_send_questions").attr("checked", !sendQuestions);
	$("#ep_cb_send_questions_text").attr("checked", sendQuestions); //needed for IE
}

function toggle_send_welcome_questions(){
	$("#ep_cb_send_questions_text").attr("checked", $("#ep_send_questions").attr("checked"));
}
 
/*
 * This function toggles the html content of the teaserArray given as argument
 */
function toggleTeaserContent(teaserArray){
	var j = rand(0, teaserArray.length-1);
	var tmpArray = new Array();
	
	//store the content of the teasers for later usage
	for (i=0;i<teaserArray.length;i++){
		tmpArray.push($(teaserArray[i]).html());
	}
	
	for (i=0;i<teaserArray.length;i++){
		//check if the last element is reached to begin with the first
		if(j>=teaserArray.length){
			j=0;
		}
		$(teaserArray[i]).html(tmpArray[j]);
		j++;
	}	
}


/*
 * This function returns a uniformly distributed pseudo random number in the given interval (including the interval borders!)  
 */
function rand (min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

/*
 * This functions writes the keyword and the searchengine  name on the position from where it is called
 * 
 * param withLogo boolean
 */
function getSearchEngineKeyword(withLogo,replaceExpr){
	 
	 var pageReferrer = document.referrer;
	
	  if (pageReferrer.indexOf('?') > -1 ) {
	  	var sDomain = pageReferrer.split('?')[0];
	  	var sQuery = pageReferrer.split('?')[1];
	  	var sEngineParam = "q";
	  	var sEngineLogo = null;
	  	var sEngineName = sDomain;
	  	
	  	if ((sDomain.indexOf('google.de') > -1 || sDomain.indexOf('google.com') > -1) && sQuery.indexOf('q=') > -1) {
   			sEngineLogo = "small_google_logo.gif";
   			sEngineName = "Google";
   			
	  	} else if (sDomain.indexOf('yahoo.com') > -1 && sQuery.indexOf('p=') > -1) {
    		sEngineParam = "p";
    		sEngineLogo = "small_yahoo_logo.gif";
    		sEngineName = "Yahoo";
  	    
  	    } else if ((sDomain.indexOf('live.com') > -1 || sDomain.indexOf('msn.com') > -1) && sQuery.indexOf('q=') > -1) {
   			sEngineLogo = "small_msn_logo.gif";
   			sEngineName = "MSN";
  	    
  	    } else if ((sDomain.indexOf('aol.de') > -1 || sDomain.indexOf('aol.com') > -1 ) && sQuery.indexOf('query=') > -1) {
    		sEngineParam = "query";
    		sEngineLogo = "small_aol_logo.gif";
    		sEngineName = "AOL"
  	    }
	  	if (sEngineLogo != null) {
    		var rePattern = new RegExp(sEngineParam + "=([^ &]*)");
	    		
				if (rePattern.exec(sQuery)) { 
		      			var aMatches = rePattern.exec(sQuery);
		      			var sKeyword = unescape(aMatches[1].replace(/\+/g," "));
		      			
		      			if(withLogo){
		      				//<![CDATA[
		      				$(replaceExpr).html('Sie suchten nach <span class="ep_bold">"' + sKeyword + '"<\/span> auf <img align="absmiddle" border="0" src="' + EMN.WebappPrefix + '/gfx/searchengines/' + sEngineLogo + '" \/>');
							//]]>
		      			} else{
		      				//<![CDATA[
		      				$(replaceExpr).html('Sie suchten nach <span class="ep_bold">"' + sKeyword + '"<\/span> auf ' + sEngineName);
							//]]>
		      			}
		    	}
	  	}
	}
}

/*
 * update provinces when the country is changed
 * 
 * param country the countrycode
 * param replaceExpr the province code to replace
 * param labelExpr the label code to replace
 */
function changeCountryAjax (country, replaceExpr, labelExpr) {
  $(replaceExpr).html('<img src="' + EMN.WebappPrefix + '/gfx/basic/loading/ajax-loading.gif" alt="busy"/>');
  $.post(EMN.WebappPrefix + "/misc/changeCountry_a.do", {country: country},
  function(data){
	$(replaceExpr).html(data);
	$(labelExpr).html($(".ep_province_country_label"));
	$(replaceExpr + " .ep_province_country_label").html("");
  });
}

/*
 * Replaces captcha when clicking a link
 *
 * param linkExpr The link to click to get new captcha
 * param imgExpr The captcha to replace
 */
function getNewCaptchaOnClick (linkExpr, imgExpr) {
  $(linkExpr).click(function() {
    $(imgExpr).attr('src', $(imgExpr).attr('src') + '#');
  });
}

/*
 * On error in purchase table, don't jump to top of page, but focus on purchase table.
 *
 */
function focusPurchaseTableOnError(){
	 if ( $('.ep_error').length >0 && $('#ep_purchaseProductTable').length >0) {
		scrollTo(0,800);
	  }
}

/*
 * Resets the value of the given element
 */
function clearElement (elementId) {
	if ($('#' + elementId).val().charCodeAt($('#' + elementId).val().length-1) == EXAMPLE_TEXT_MARKER) {
		$('#' + elementId).val("");
		$('#' + elementId).removeClass("ep_special_hint");;
	};
}

/*
 * Opens the VIP info page
 */
function openVipInfoPage () {
	var vipinfo = window.open(EMN.WebappPrefix + "/vip/info.do", "", "width=980, height=980, resizable=yes , scrollbars=yes");
	vipinfo.focus();
}

/*
 * Hides and show the selected payment form for additional claim
 */
function hideShowAddtionalClaimPaymentData(radioBox, formData, idName) {
	for (i=0;i<formData.payment_type.length;i++){
		var hideElem = '#' + idName + formData.payment_type[i].value
		$(hideElem).hide();
	}
	var elem = '#' + idName + radioBox.value
	$(elem).show();
};
