/* DPWN library
 * page: constansts and page related functions
 * .pif: piflibrary (ajax, validation, js-actions)
 */
var dpwn = {
	/* page related functions */
	page: {
		/* general page messages, filled from glossary */
		messages: {},
		/* add function OBEJCT or list of function OBJECTS which is/are called on document ready */
		ready: function(callback) {
			if (typeof callback != 'function' && callback.length) {
				for (var i=0; i<callback.length; i++) {
					if ($.browser.msie) dpwn.page.load(callback[i]);
					else $(document).ready(callback[i]);
				}
			}
			else {
				if ($.browser.msie) dpwn.page.load(callback);
				else $(document).ready(callback);
			}
		},
		_loadCalls: [],
		/* add function OBJECT or STRING which is called on document load */
		load: function(callback) {
			dpwn.page._loadCalls.push(callback);
		},
		_unloadCalls: [],
		/* add function OBJECT or STRING which is called on document unload */
		unload: function(callString) {
			dpwn.page._unloadCalls.push(callString);
		},
		_execLoadCalls: function() {
			for(var i=0; i<dpwn.page._loadCalls.length; i++) {
				try {
					var callback = dpwn.page._loadCalls[i];
					if (typeof callback == 'string') eval(callback);
					else callback();
				}
				catch (e) {}
			}
		},
		_execUnloadCalls: function() {
			for(var i=0; i<dpwn.page._unloadCalls.length; i++) {
				try {
					var callback = dpwn.page._unloadCalls[i];
					if (typeof callback == 'string') eval(callback);
					else callback();
				}
				catch (e) {}
			}
		},
		/* adds print link to .foot-area .print if not printpreview */
		addPrintlink: function(url, width) {
			if (location.search.indexOf('print=true') > -1 || location.hash.indexOf('print=true') > -1) return;
			if ($('div.foot-area p.print').size()) {
				var printlink = '<a href="#" onclick="return dpwn.page.printView(null, 735);">'+ dpwn.page.messages.PRINT_TEXT +'</a>';
				$('div.foot-area p.print').prepend(printlink);
			}
		},
		/* opens popup with print view */
		printView: function(url, width) {
			url = (url || location.href).replace(location.hash, '');
			width = width || 588;
			printparam = (url.indexOf('?') > -1) ? '&amp;print=true' : '?print=true'
			return this.popup(url + printparam, width, 500, -1, -1, false, 'toolbar=1,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1', 'printpopup');
		},
		/* disables links, buttons, forms and inserts print head for DPAG */
		initPrintView: function() {
			if (location.search.indexOf('print=true') == -1 && location.hash.indexOf('print=true') == -1) return;

			$("a").each(function() {
				if($(this).attr("id") != 'printfooter' && $(this).attr("id") != 'printheaderbutton') {
					$(this).removeAttr("href");
					$(this).removeAttr("onclick");
					$(this).removeAttr("onmouseover");
					$(this).removeAttr("onmouseout");
				}
			});
			$("input[@type='submit']").each(function() {
				this.onclick = function(){return false;}
			});
			$("input[@type='file']").each(function() {
				this.setAttribute("disabled", "true");
			});
			$("form").each(function() {
				this.onsubmit = function(){return false;}
				this.removeAttribute("action", "false");
			});
			// DPAG: add print head
			if (location.href.indexOf('/dpag') > -1) {
				var url = location.href.replace('&lang=', '&amp;lang=').replace('&print=true', '').replace('?print=true&', '?');;
				var printhead = '<div class="printbar">'
				var printfoot = printhead;
				printhead += ' <button onclick="print();">'+ dpwn.page.messages.PRINT_NOW_TEXT +'</button>';
				var printfoot = printhead;
				printfoot += '</div>';
				printhead += ' <h2>URL: '+ url +'</h2>';
				printhead += '</div>';
				$('div.head-area').prepend(printhead);
				if ($('p.copyright').size()) $('p.copyright').append(printfoot); // page
				else $('div.foot-area').append(printfoot); // popup
			}
		},
		/* adds close buttton to .head-area if not printpreview */
		addPopupbar: function(url, width) {
			if (location.search.indexOf('print=true') > -1 || location.hash.indexOf('print=true') > -1) return;
			if ($('div.type-popup div.head-area').size() || $('div.type-flash div.head-area').size()) {
				var closebar = '<a href="#" onclick="window.close()">'+ dpwn.page.messages.CLOSE_TEXT +'</a>';
				$('div.type-popup div.head-area').prepend(closebar);
				$('div.type-flash div.head-area').prepend(closebar);
			}
		},
		popupwindow: false,
		/* notused was linkfield */
		popup: function(url, width, height, left, top, NOTUSED, options, winname) {
			var screenW = screen.availWidth || 800;
			var screenH = screen.availHeight || 600;

			width = Math.min(width || (screenW - 100), screenW - 100);
			height = Math.min(height || (screenH - 100), screenH - 100);

			left = (left && left > 0) ? left : (screenW - width) / 2;
			top = (top && top > 0) ? top : (screenH - height) / 2 - 20;

			options = options || 'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1';
			winname = winname || 'w';
			// check if popup already open
			if (self.DPWN_IS_POPUP && winname == 'w') winname = 'w2';

			if(dpwn.page.popupwindow && (dpwn.page.popupwindow.closed != true)) dpwn.page.popupwindow.close();

			dpwn.page.popupwindow = window.open(dpwn.util.escapeZoomURL(url), winname, options+',width='+width+',height='+height+',left='+left+',top='+top);
			try {
				dpwn.page.popupwindow.DPWN_IS_POPUP = 1;
				}
			catch (e) {} // error if not a dpwn window, but not needed then
			dpwn.page.popupwindow.focus();
			// close self if it was a popup
			if (self.DPWN_IS_POPUP && winname == 'w2') {
				dpwn.page.popupwindow.name = 'w';
				self.close();
			}

			return false;
		},
		/* do not close if already a popup */
		popupclose: function() {
			if(!self.DPWN_IS_POPUP && dpwn.page.popupwindow && (dpwn.page.popupwindow.closed == false)) dpwn.page.popupwindow.close();
		},
		skin: (document.location.href.indexOf('skin=lo') > -1) ? 'lo' : 'hi',
		checkVersion: function() {
			var loc = document.location;
			if (loc.search.indexOf('check=no') != -1 || loc.hostname.indexOf('search.') != -1 || loc.pathname.indexOf('/forms') != -1 || loc.pathname.indexOf('/app') != -1) return;
			var currentVersion = dpwn.page.skin;
			var intendedVersion = (screen.availWidth > 800) ? "hi" : "lo";
			if(currentVersion != intendedVersion) {
				if(currentVersion == "lo") {
					dpwn.page._switchToVersion("hi");
				} else {
					dpwn.page._switchToVersion("lo");
				}
			}
		},
		_switchToVersion: function(version) {
			var url 	= document.location;
			var newUrl;
			if(version == 'hi') {
				if(url.href.indexOf('&skin=lo') != -1) newUrl = url.href.replace(/&skin=lo/,"");
				if(url.href.indexOf('?skin=lo&') != -1) newUrl = url.href.replace(/skin=lo&/,"");
				if(url.href.indexOf('?skin=lo') != -1) newUrl = url.href.replace(/skin=lo/,"");
			} else {
				if(url.href.indexOf('skin=hi') != -1) {
					newUrl = url.href.replace(/skin=hi/,"skin=lo");
				} else {
					newUrl = url.pathname;
					newUrl += (url.search) ? url.search + '&skin=lo' : '?skin=lo';
					if(url.hash != "") newUrl += url.hash;
				}
			}
			setTimeout("document.location = '" + newUrl + "'",1000);
		},
		/*
		 * Functions/Properties related to specific modules
		 */
		modules: {
			/*
			 * label [i] icons with text get click to show info text, initialized for ALL clients
			 */
			prepareLabelPopup: function() {
				$("body").append('<div id="helpicon-helptext" class="structured-text"></div>');
				$('span.help-icon').each(function() {
					var t = $(this);
					var tooltip = t.next('.help-text').eq(0);
					var tooltipContent = t.next('.help-text').eq(0).html();
					
					var event = (dpwn.page.CLIENT && dpwn.page.CLIENT == 'DHL') ? 'mouseover' : 'click'
					
					t[event](function() {
						var posX = tooltip.offset().left - 30;
						var posY = tooltip.offset().top + 14;
						
						if(dpwn.page.CLIENT && dpwn.page.CLIENT == 'DHL') posY = posY+2;
						
						if(posX + 300 > $(document).innerWidth()) posX = $(document).innerWidth() - 300;
						
						if($(t).attr("class").indexOf("help-icon-active") == -1) {
							$("#helpicon-helptext").hide();
							$('span.help-icon').removeClass("help-icon-active");
							$("#helpicon-helptext").html(tooltipContent);
							$("#helpicon-helptext").css("left", posX).css("top", posY);
							$("#helpicon-helptext").slideDown('fast');
							$(t).addClass("help-icon-active");
						} else if (event == 'click') {
							// close but only on click (not DHL)
							$("#helpicon-helptext").slideUp('fast');
							$('span.help-icon').removeClass("help-icon-active");
						}
						return false;
					});
				});
				$("#helpicon-helptext").click(function(){
					$(this).fadeOut('fast');
					$('span.help-icon').removeClass("help-icon-active");
				});
			},
			/*
			 * Video control functions used by video template in common.xsl
			 */
			prepareVideo: function(VideoLocation, id) {
				if(VideoLocation != 'auswahl') {
					if (VideoLocation.indexOf('.zip') > 1) {
						document.location = VideoLocation;
					} else {
						var VideoArray = VideoLocation.split('|');
						this.showVideo(VideoArray[0], id, VideoArray[1], VideoArray[2]);
					}
				}
			},
			showVideo: function(url, divId, breit, hoch) {
				var html = 	'<table border="0" cellpadding="0" cellspacing="0" width="100%">\n'+
							'	<tr>\n'+
							'		<td>\n'+
							'			<OBJECT ID="'+divId+'" name="'+divId+'" CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" HEIGHT="'+ hoch +'" WIDTH="'+ breit +'">\n'+
							'				<PARAM NAME="controls" VALUE="ImageWindow">\n'+
							'				<PARAM NAME="console" VALUE="Clip'+divId+'">\n'+
							'				<PARAM NAME="autostart" VALUE="false">\n'+
							'				<PARAM NAME="src" VALUE="'+url+'">\n'+
							'				<EMBED SRC="'+url+'" type="audio/x-pn-realaudio-plugin" CONSOLE="'+divId+'" CONTROLS="ImageWindow" HEIGHT="'+ hoch +'" WIDTH="'+ breit +'" AUTOSTART="false"></embed>\n'+
							'			</OBJECT>\n'+
							'		</td>\n'+
							'	</tr>\n'+
							'	<tr>\n'+
							'		<td>\n'+
							'			<OBJECT ID="'+divId+'" CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" HEIGHT="30" width="'+ breit +'">\n'+
							'				<PARAM NAME="controls" VALUE="ControlPanel">\n'+
							'				<PARAM NAME="console" VALUE="Clip'+divId+'">\n'+
							'				<PARAM NAME="autostart" VALUE="true">\n'+
							'				<EMBED type="audio/x-pn-realaudio-plugin" CONSOLE="'+divId+'" CONTROLS="ControlPanel" HEIGHT="30" width="'+ breit +'" AUTOSTART="true"></embed>\n'+
							'			</OBJECT>\n'+
							'		</td>\n'+
							'	</tr>\n'+
							'</table>\n';
				$("#" + divId).html(html);
			},
			/*
			 * Video control functions used by videochoice template in common.xsl & dpwn/video.xsl
			 */
			hideVideoLayer: function(id) {
				document.getElementById("videoChoice_"+id+"_Player").style.display = "none";
				document.getElementById("videoChoice_"+id+"_Player_Cont").innerHTML = "";
				document.getElementById("videoChoice_"+id+"_Select").style.display = "block";
			},
			showVideoV2: function(node,id) {
				var video 		= node.videoChoiceSelect[node.videoChoiceSelect.selectedIndex].value;

				if(video != "none" && video != "") {
					var ext_end 	= (video.indexOf("?") != -1) ? video.indexOf("?") : video.length;
					var file_ext 	= video.substring(video.lastIndexOf(".")+1,ext_end);
					var src 		= video.substring(0,video.indexOf("?"));
					var width 		= 320;
					var height 		= 240;

					if(src.indexOf("/") == 0) {
						src = document.location.href.substring(0, document.location.href.indexOf(document.location.pathname)) + src;
					}

					//Get width and height values from string
					if(video.indexOf("?") != -1) {
						var temp = video.split("?");
						temp = temp[1].split("&");
						for(i=0;i<temp.length;i++) {
							var keyval = temp[i].split("=");
							if(keyval[0] != "" && keyval[1] != "") eval(keyval[0] + "=" + keyval[1]);
						}
					}

					var player_cont = '<div class="videoChoiceContPlayer" align="center">';

					if(file_ext == "wmv") {
						height = height + 46; //Add height for player controls
						player_cont += 	'<OBJECT type="application/x-oleobject" CLASSID="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" HEIGHT="'+height+'" WIDTH="'+width+'">'+
										'	<PARAM NAME="showControls" VALUE="true">'+
										'	<PARAM NAME="autostart" VALUE="true">'+
										'	<PARAM NAME="url" VALUE="'+src+'">'+
										'	<EMBED SRC="'+src+'" autoplay="true" controller="true" enablejavascript="true" HEIGHT="'+height+'" WIDTH="'+width+'" AUTOSTART="true"></embed>'+
										'</OBJECT>';
					} else if(file_ext == "rm") {
						player_cont += 	'<OBJECT ID="id" name="id" CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" HEIGHT="'+height+'" WIDTH="'+width+'">'+
			 							'	<PARAM NAME="controls" VALUE="ImageWindow">'+
										'	<PARAM NAME="console" VALUE="video_'+id+'">'+
										'	<PARAM NAME="autostart" VALUE="false">'+
										'	<PARAM NAME="src" VALUE="'+src+'">'+
										'	<EMBED SRC="'+src+'" type="audio/x-pn-realaudio-plugin" CONSOLE="video_'+id+'" CONTROLS="ImageWindow" HEIGHT="'+height+'" WIDTH="'+width+'" AUTOSTART="false"></embed>'+
										'</OBJECT>'+
										'<OBJECT ID="" CLASSID="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" HEIGHT="30" width="'+width+'">'+
										'	<PARAM NAME="controls" VALUE="ControlPanel">'+
										'	<PARAM NAME="console" VALUE="video_'+id+'">'+
										'	<PARAM NAME="autostart" VALUE="true">'+
										'	<EMBED type="audio/x-pn-realaudio-plugin" CONSOLE="video_'+id+'" CONTROLS="ControlPanel" HEIGHT="30" width="'+width+'" AUTOSTART="true"></embed>'+
										'</OBJECT>';
					} else if(file_ext == "mov") {
						player_cont += 	'<OBJECT ID="x" name="x" CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab" HEIGHT="'+height+'" WIDTH="'+width+'">'+
										'	<PARAM NAME="controller" VALUE="true">'+
										'	<param name="type" value="video/quicktime">'+
										'	<PARAM NAME="autostart" VALUE="true">'+
										'	<PARAM NAME="src" VALUE="'+src+'">'+
										'	<PARAM NAME="pluginspage" VALUE="http://www.apple.com/quicktime/download/">'+
										'	<EMBED SRC="'+src+'" type="video/quicktime" autoplay="false" controller="true" enablejavascript="true" HEIGHT="'+height+'" WIDTH="'+width+'" AUTOSTART="true" PLUGINSPAGE="http://www.apple.com/quicktime/download/indext.html"></embed>'+
										'</OBJECT>';
					} else {
						document.location = video;
						return false;
					}

					player_cont += 	'</div>';

					document.getElementById("videoChoice_"+id+"_Player_Cont").innerHTML = player_cont;
					document.getElementById("videoChoice_"+id+"_Select").style.display = "none";
					document.getElementById("videoChoice_"+id+"_Player").style.display = "block";
				}

				return false;
			},
			/*
			 * If anchorlink on a question in FAQ open this question
			 * used by all clients except DPAG
			 */
			anchorFAQ: function() {
				if (window.location.hash.indexOf('question') == -1) {
					return;
				} else {
					var anker 			= window.location.hash;
					var questionid 		= anker.substring(1, anker.length);
					var questionid 		= questionid.replace(/\./g, "_");
					var innerOnclick 	= $("#" + questionid + " a").attr("onclick");

					if(typeof innerOnclick == "string") {
						innerOnclick = innerOnclick.replace('return', '');
						eval(innerOnclick);
					} else if(typeof innerOnclick == "function") {
						innerOnclick();
					}
				}
			},
			toggleFAQ: function(faq) {
				$('#'+faq).toggle();
				/*
				 *	Track selected question if Omniture Tracking is active
				 */
				if(dpwn.page.DO_OMNITURE && dpwn.page.DO_OMNITURE_FAQ_TRACKING && $('#'+faq).css("display") == 'block') {
					var question_header = $('#'+faq).prev("h3");
					var question 		= question_header.children("a").text();
					var question_nr 	= question_header.attr("id");

					var s=s_gi(s_account);
					s.linkTrackVars='prop6,prop15,prop16';
					s.prop15=s.pageName;
					s.prop16=s.hier1;
					s.prop6=question;
					
		 			s.tl(question_header.children("a").get(0),'o','FAQs: '+question_nr);
				}
				return false;
			},
			toggleHeaderInfo: function(id) {
				$('#'+id).toggle();
				return false;
			},
			select_popups: {},
			/*
			 * ele may be a FORM element (DHL, DPWN) or the SELECT element itself (DPAG)
			 */
			handleSelectPopups: function(ele) {
				if (ele.nodeName == 'FORM') {
					var name = $(ele).attr('name');
					var select = ele.elements['href'];
				}
				else { // SELECT
					var name = $(ele).parents('form').attr('name');
					var select = ele;
				}

				var index = select.selectedIndex;
				var value = select[index].value;
				var servlet = $(select).parents('form').get(0).elements["url"].value;

				// no href or DPWN quicklinks 1st item should do nothing!
				if (value == "#" || value == "" || (index == 0 && select.id == "dpwn-quicklink-select")) {
					return false;
				}

				if(value.indexOf("http") != 0 && value.indexOf("ftp:") != 0 && value.indexOf("mailto:") != 0 && value.indexOf("/") != 0) {
					value = servlet + value;
				}

				var item = this.select_popups[name][index];

				if (item && item.width) {
					return dpwn.page.popup(item.href, item.width, item.height);
				}
				else if (item) {
					var x = window.open(value);
					if (x) return false;
					else return true;
				}
				else {
					window.location.href = value;
					return false;
				}
			},
			extendStepNavigation: function() {
				$('a.stepnavi-extended').each(function() {
					$(this).click(function() {
						return dpwn.pif.actions._stepNaviSubmit(this);
					})
				});
			}
		},
		/*
		 * Misc. functions
		 */
		misc: {
			setFlashVar: function(flashid,variable,value) {
				if(value == "COOKIE.ZS_SESSIONID") {
					value = $.cookie("ZS_SESSIONID");
				}
				
				//This fixes issues with initializing Flashes in Opera and general 
				//issues with initializing flashes within FAQ-Answers which are display=none;
				if(typeof $("#"+flashid).get(0).SetVariable == 'undefined') {
					var recall = setTimeout("dpwn.page.misc.setFlashVar('"+flashid+"','"+variable+"','"+value+"')",1000);
					return false;
				}
				
				$("#"+flashid).get(0).SetVariable(variable, value);
			},
			submitFOCUS: function(item) {
				if (document.all && item.className) {
					var currentClass = item.className;
					if (currentClass.indexOf('SubmitFOCUS') == -1) {
						item.className = currentClass.replace('Submit', 'SubmitFOCUS');
					} else {
						item.className = currentClass.replace('SubmitFOCUS', 'Submit');
					}
				}
			}
		}
	},
	util: {
		/*
		 * Escapes alt and title parameter values or href value because xsl does not escape these.
		 */
		escapeZoomURL: function(url) {
			if (url.indexOf('title=') > -1 || url.indexOf('alt=') > -1) {
				var part = url.split('&');
				url = '';
				for (i=0; i < part.length; i++) {
					//first is href + first param!
					var param = part[i].split('=');
					url = url + param[0] + '=' + escape(param[1]);
					if (i < part.length) url += '&';
				}
			}
			if (url.indexOf('disclaimer.jsp') > -1) {
				var part = url.split('target=');
				url = part[0] + 'target=' + escape(part[1]);
			}
			return url;
		},
		getURLParam: function(url,param) {
			if(url.indexOf("?") > -1 ) {
	    		var url 	= url.substr(url.indexOf("?")+1);
				var keyvals	= url.split("&");

				for(var i=0;i<keyvals.length; i++) {
					if(keyvals[i].split("=")[0] == param) return keyvals[i].split("=")[1];
				}
	  		}
			return null;
		}
	},
	/* PIF related functions */
	pif: {
		/* ajax related functionality */
		ajax: {
			calendar: {
				/* display data preloaded or load new via ajax */
				_showData: function(day) {
					dpwn.pif.ajax.calendar._hideAllData();
					if ($('div.temp', day).html()) {
						$('div.temp', day).show();//fadeIn('fast');
					}
					else {
						var url = dpwn.pif.ajax.SERVLET + '?action=calendardata&date=' + $('a', day).attr('rel').substr(4);
						$.getJSON(url, function(json) {
							if (json.calendardata) {
								day.append('<div class="temp">' + json.calendardata + '</div>');
								var temp = $('div.temp', day);
								temp.hover(function() {}, function() { temp.hide(0); });
								dpwn.pif.ajax.calendar._showData(day);
							}
						});
					}
				},
				/* hide all open infos */
				_hideAllData: function() {
					$('div.calendar div.temp').hide(0);
				}
			},
			/* bind actions to relevant modules, currently "calendar" only */
			bindActions: function(){
				/* CALENDAR: */
				// on mouseover show preloaded data or load new
				$('div.calendar td[a.calendar-event-link]').each(function() { // div. needed as Jquery upto 1.1.2 has a bug!
					var day = $(this);
					$(this).hover(function() { dpwn.pif.ajax.calendar._showData(day); }, function() {})
				});
				 // on mouseout hide all calendardata
				$('div.calendar table.calendar-table').each(function() {
					$(this).hover(function() {}, dpwn.pif.ajax.calendar._hideAllData);
				});
				// hide preloaded temps on mouseout
				$('div.calendar div.temp').each(function() {
					var temp = $(this);
					temp.hover(function() {}, function() {
						temp.hide(0);
						});
				});
			},
			TIMEOUT: 3000,
			_showWait: function(application) {
				var wait = $('div.ajaxloading', application);
				if (!wait.html()) {
					var w = application.outerWidth();
					var h = application.outerHeight();
					application.prepend('<div class="ajaxloading"></div>');
					wait = $('div.ajaxloading', application);
					wait.css('width', w);
					wait.css('height', h);
					wait.css('opacity', '0.8');
				}
				wait.fadeIn();
			},
			_hideWait: function(application) {
				$('div.ajaxloading', application).hide(0);
			},
			/*
			 * do a GET or POST ajax submit
			 *
			 * request expects: xmlFile, lang, context and datafields
			 */
			submit: function (srcNode, method, validate) {
				/* srcNode: added by calling function, not XSL */
				var form = srcNode.form;
				if(validate == 'true' && !dpwn.pif.validation.validateForm(form, true)) {
					return;
				}
				method = method || 'GET';
				var application = $(srcNode).parents("div.application");
				var get	= $(form).formSerialize();
				var p = dpwn.page;

				var context = $('input[@name="PA.CONTEXT"]', $(application)).get(0).value;

				get += '&skin=' + p.SKIN;
				get += '&check=' + p.CHECK;
				get += '&tab=' + p.TAB;
				get += '&isSecure=' + p.IS_SECURE;
				get += '&_=' + encodeURI(Math.random()); // IE extra param
				//dpwn.pif.ajax._showWait(application);
				try {
					$.ajax({
						url: dpwn.pif.ajax.SERVLET + '?' + get,
						type: method,
						dataType: 'json',
						success: function(data, statusmsg) {
							//dpwn.pif.ajax._hideWait(application);
							dpwn.pif.ajax._submitCallback(data, statusmsg, application)
							},
						error: function(e, errorstr) {
							//dpwn.pif.ajax._hideWait(application);
							dpwn.pif.ajax._errorCallback(e, errorstr, application)
							},
						timeout: dpwn.pif.ajax.TIMEOUT //ms
						}
					);
				}
				catch (e) {
					return dpwn.pif.ajax._errorCallback(200, 'timeout', application)
				}
			},
			/*
			 * submit callback
			 */
			_submitCallback: function(data, statusmsg, application) {
				try {
					// response with redirect but with status code 200 and { "redirect": URI }
					if (data.redirect) {
						location.href = data.redirect;
						return;
					}
					// response with content
					var context = data.context //$.trim(text.substring(0, text.indexOf(MODELS_CUT)));
					var text = data.text;
					// get new content
					var MODELS_CUT = '###PIF_AJAX_MODELS###';
					var MENUCONTENT_CUT = '###PIF_AJAX_MENUCONTENT###';
					var HEADER_CUT= '###PIF_AJAX_HEADER###';
					var MAINCONTENT_CUT = '###PIF_AJAX_MAINCONTENT###';
					var CRBS_CUT = '###PIF_AJAX_CRBS###';
					var script = text.substring(text.indexOf(MODELS_CUT)+MODELS_CUT.length,
						text.indexOf(MENUCONTENT_CUT));
					var menucontenthtml = text.substring(text.indexOf(MENUCONTENT_CUT)+MENUCONTENT_CUT.length,
						text.indexOf(HEADER_CUT));
					var headerhtml = text.substring(text.indexOf(HEADER_CUT)+HEADER_CUT.length,
						text.indexOf(MAINCONTENT_CUT));
					var maincontenthtml = text.substring(text.indexOf(MAINCONTENT_CUT)+MAINCONTENT_CUT.length,
						text.indexOf(CRBS_CUT));
					var crbshtml = text.substring(text.indexOf(CRBS_CUT)+CRBS_CUT.length);
					// target divs
					var header 		= '#pageHeader/h1';
					var menucontent = '*[@id="APP_CONTEXT_'+context+'_menucontent"]';
					var maincontent = '*[@id="APP_CONTEXT_'+context+'_maincontent"]';
					var crbs 		= '*[@id="APP_CONTEXT_'+context+'_crbs"]';

					// set new content
					if (headerhtml) 		$(header).each(function(){ this.innerHTML = headerhtml; });
					if (menucontenthtml) {
						$(menucontent).each(function(){
							this.innerHTML = menucontenthtml;
						});
					}
					if (maincontenthtml) {
						$(maincontent).each(function(){
							this.innerHTML = maincontenthtml;
						});
					}
					if (crbshtml) {
						$(crbs).each(function(){
							this.innerHTML = crbshtml;
						});
					}

					// gets new validation and actions
					eval(script);
					dpwn.pif.models[context] = getnewmodels(context);
					dpwn.pif.actions.bindActions();
				}
				catch(e) {
					this._errorCallback('200', 'timeout', application)
				}
			},
			/*
			 * ajax error callback, handles timeout 302, 404 and 500
			 * if an error occured a simple submit is done
			 */
			_errorCallback: function (e, errorstr, application) {
				var dummySrcNode = $('form/input[@name="PA.CONTEXT"]',application)[0];
				dpwn.pif.actions._submitForm(dummySrcNode, false);
				return false;
				/*
				var timeout = false;
				try {
					if (!e.status || (0 == e.status)) { // probably timeout
						timeout = true;
					}
				}
				catch (e) { // Firefox throws...
					timeout = true;
				}
				if (timeout) {
				var status = e.status;
				if (404 == status || 500 == status) {
				*/
			}
		},
		messages: {
			// defaultvalidation errormessages
			PLEASE_WAIT: 'Bitte warten',
			TEXT_TRUNCATED: 'Der Text wurde auf die maximale Eingabemöglichkeit von ##maxlength## Zeichen gekürzt.',
			VALIDATION_REQUIRED: 'Das Feld "##pif_cv_fieldlabel##" ist ein Pflichtfeld.',
			VALIDATION_REGEXP: 'Der Eintrag in Feld "##pif_cv_fieldlabel##" hat ein falsches Format.',
			VALIDATION_TYPE: 'Die Eingabe im Feld "##pif_cv_fieldlabel##" entspricht nicht dem erwarteten Typ.',
			VALIDATION_MINLENGTH: 'Der Eintrag in Feld "##pif_cv_fieldlabel##" ist zu kurz.',
			VALIDATION_MAXLENGTH: 'Der Eintrag in Feld "##pif_cv_fieldlabel##" ist zu lang.',
			VALIDATION_MINVALUE: 'Der Wert in Feld "##pif_cv_fieldlabel##" ist zu klein.',
			VALIDATION_MAXVALUE: 'Der Wert in Feld "##pif_cv_fieldlabel##" ist zu groß.'
			// default ajax errormessages -->
			/*
			HTTP_UNKNOWN: 'Ein unbekannter Fehler ist aufgetreten.',
			TIMEOUT: 'Zeitüberschreitung',
			404: 'Seite nicht gefunden.',
			500: 'Applikations Fehler.'
			*/
		},
		util: {
			/*
			 * show msg on erroroutput
			 * @param STRING msg
			 * @param JQUeryObject erroroutput or 1st erroroutput element found
			 */
			showerror: function (msg, appContainer) {
				if (!appContainer) erroroutput = $($('.erroroutput').get(1));
				else erroroutput = $('.erroroutput', appContainer);
				erroroutput.html(msg).fadeIn();
			},
			/*
			 * Returns the input type of the form element passed to this function
			 *
			 * @el NODE-OBJECT
			 */
			getInputType: function(el) {
				var thisInputType = el.type;
				if(thisInputType == undefined && el[0]) {
					thisInputType	= el[0].type;
					if(thisInputType == "checkbox") thisInputType = "checkboxgroup";
				}
				return thisInputType;
			},
			/*
			 * Returns the ID of the label associated with the form element that is passed to this function.
			 *
			 * @el NODE-OBJECT
			 */
			getLabelId: function(el) {
				return (this.getInputType(el) == "radio" || this.getInputType(el) == "checkboxgroup") ? "label_" + el[0].id : "label_" + el.id;
			},
			/*
			 * Returns the number of properties in an object. A simple atempt to copy the Array.length property
			 *
			 * @o OBJECT
			 */
			propertyCount: function(o) {
				var c=0;
				for(var x in o) {
					c++;
				}
				return c;
			}
		},
		/*
		 * PIF3 Client form validation
		 */
		validation: {
			// Settings and constants related to the PIF3 Client form validation
			settings: {
				/*
				 * General validation settings
				 */
				doValidation: true,
				/*
				 * RegExp Constants
				 */
				__ZIPCODE__: "/^([0-9][0-9][0-9][0-9][0-9])+$/",
				/*
				 * Regular Expressions for eMail validation. These were adopted
				 * from RuleEmail.java, which is used for Server-Side validation.
				 */
				EMAIL_GROUP_3_PATTERN			: /^(.+)@(.+)\.(.+)$/,
				EMAIL_GROUP_2_PATTERN			: /^(.+)@(.+)$/,
				EMAIL_USER_PATTERN				: /^[a-zA-Z0-9]([\._-]?[a-zA-Z0-9]+)*$/,
				EMAIL_SYMBOLIC_DOMAIN_PATTERN	: /^[a-zA-Z0-9]([\._-]?[a-zA-Z0-9]+)*$/,
				EMAIL_TLD_PATTERN				: /^([a-zA-Z0-9]{2,})$/,
				EMAIL_IP_DOMAIN_PATTERN			: /^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/
			},
			/*
			 * Checks for valid email format. Adopted from RuleEmail.java,
			 * which is used for Server-Side email validation.
			 *
			 * @email STRING
			 */
			_checkEMail: function(email) {
				var eMailCheck 	= false;
				var eMailParts 	= email.match(this.settings.EMAIL_GROUP_3_PATTERN);

				if(eMailParts) { //eMail is well formed
					eMailCheck = eMailParts[1].match(this.settings.EMAIL_USER_PATTERN);
					if(eMailCheck) { //User-Part is valid

						eMailCheck = (eMailParts[2].match(this.settings.EMAIL_SYMBOLIC_DOMAIN_PATTERN) && eMailParts[3].match(this.settings.EMAIL_TLD_PATTERN));
						if(!eMailCheck) { //Domain AND/OR TLD is invalid. Check for IP
							eMailParts = email.match(this.settings.EMAIL_GROUP_2_PATTERN);
							if(eMailParts) {
								eMailCheck = eMailParts[2].match(this.settings.EMAIL_IP_DOMAIN_PATTERN);
							}
						}
					}
				}
				return eMailCheck ? true : false;
			},
			/*
			 * Clears any error output that may have been generated by a previous validation
			 *
			 * @form NODE-OBJECT Node Object of the <form> Element
			 */
			_clearErrorOutput: function(form) {
				if($("#erroroutput_" + form.id)) $("#erroroutput_" + form.id).html("").hide();
				if($("div.textblock.error", form)) $("div.textblock.error", form).html("").hide();
				if($("div.textblock.errorblock", form)) $("div.textblock.errorblock", form).html("").hide();
				$("label",form).removeClass("errorlabel");
				$("legend",form).removeClass("errorlabel");
			},
			/*
			 * Generates the error messages and highlights invalid fields
			 *
			 * @form NODE-OBJECT Node Object of the <form> Element
			 * @errors OBJECT The errors Object generated by this._doValidation
			 */
			_writeErrorOutput: function(form, errors) {
				var context 	= form["PA.CONTEXT"].value;
				var validation 	= dpwn.pif.models[context].validation;

				/*
				 * Sort errors in the order of the elements appearance in the page.
				 */
				var errors_sorted = {};
				for(var i=0;i<form.elements.length;i++) {
					if(errors[form.elements[i].name] && !errors_sorted[form.elements[i].name]) {
						errors_sorted[form.elements[i].name] = errors[form.elements[i].name];
					}
				}

				for(var nodeName in errors_sorted) {
					var error	= errors_sorted[nodeName];
					var el 		= form[nodeName];
					var valDef 	= validation[nodeName];

					output = (valDef["error_" + error.type]) ? valDef["error_" + error.type] : dpwn.pif.messages["VALIDATION_" + error.type.toUpperCase()];
					output = output.replace(/##pif_cv_fieldlabel##/,$("#"+dpwn.pif.util.getLabelId(el)).html().replace(/\*/, ""));
					output = output.replace(/##pif_cv_fieldvalue##/,el.value);

					hasErrorBlock = false;
					if(valDef.show == "block") {
						errorBlock = (el.length != undefined) ? el[0] : el; //Special treatment for radio and checkboxgroups
						while(!hasErrorBlock) {
							if(errorBlock == form || errorBlock == document) break;
							if(errorBlock.previousSibling != null) {
								errorBlock = errorBlock.previousSibling;

								if(errorBlock.nodeType == 1 && errorBlock.className.indexOf("textblock") != -1 && (errorBlock.className.indexOf("error") != -1)) hasErrorBlock = true;
							} else {
								errorBlock = errorBlock.parentNode;
							}
						}
					}

					if(hasErrorBlock) {
						$(errorBlock).append(output + "<br/>").show();
					} else if($("#erroroutput_"+form.id)) {
						$("#erroroutput_"+form.id).append(output + "<br/>").show();
					}

					if($("#"+dpwn.pif.util.getLabelId(el))) $("#"+dpwn.pif.util.getLabelId(el)).addClass("errorlabel");
				}
			},
			/* tries to convert an XPath to a JS expression, result must be used in try/catch block as it may contain
			 * an invalid JS expression, e.g. mod or xpath function do not work
			 * = => ==
			 * div => /
			 * or => ||
			 * and => &&
			 * not( =>!(
			 * true() => true
			 * false() => false
			 * APP.x-y => APP.x$y
			 * [int] => [int - 1]
			 * child::APP. =>
			 * returns false if xpath could not be converted properly
			 */
			_xPath2expression: function(xpath) {
				var exp = xpath;
				exp = exp.replace(/=/gi, '==');
				exp = exp.replace(/child\:\:APP\./gi, function(w){return w.replace(/child\:\:/, '')});
				exp = exp.replace(/[\)\]\s]*div[\(\s]/gi, function(w){return w.replace(/div/, '/')});
				exp = exp.replace(/[\)\]\s]*or[\(\s]/gi, function(w){return w.replace(/or/, '||')});
				exp = exp.replace(/[\)\]\s]*and[\(\s]/gi, function(w){return w.replace(/and/, '&&')});
				exp = exp.replace(/[\)\]\s]*not\(/gi, function(w){return w.replace(/not/, '!')});
				exp = exp.replace(/[\)\]\s]*true\(\)/gi, function(w){return w.replace(/true\(\)/, 'true')});
				exp = exp.replace(/[\)\]\s]*false\(\)/gi, function(w){return w.replace(/false\(\)/, 'false')});
				exp = exp.replace(/APP\.[-_a-z0-9]+/gi, function(w){return w.replace('-', '$')});
				try {
					exp = exp.replace(/[[0-9]+\]/gi, function(w){var v = parseInt(w.substr(1, w.length-2))-1; return '['+v+']';});
				}
				catch (e) {
					return false; // could not be converted
				}
				return exp;
			},
			/* builds dict object from form values, form names may only contain -_a-zA-Z0-9 but no . */
			_form2Object: function (form) {
				var APP = {};
				try {
					for (var i=0; i<form.elements.length; i++) {
						var f = form.elements[i];
						if (f.name && f.name.indexOf('APP.') == 0) {
							var n = f.name.substr(4).replace('-', '$'); // x-y => x$y
							// . in fieldname should not happen
							if (n.indexOf('.') != -1) return false;

							var t = f.type;
							var v = undefined;

							if (t == 'text' || t == 'textarea' || t == 'password') {
								v = f.value;
							}
							else if (t == 'checkbox' && form[f.name].length > 1) {
								if (n in APP && APP[n] instanceof Array) { // checkboxgroup 2nd and higher element
									v = APP[n];
								}
								else { // checkboxgroup 1st entry with value save as array
									v = [];
								}
								v.push((f.checked) ? f.value : undefined);
							}
							else if (t == 'checkbox') { // single check if checked only
								if (f.checked) v = f.value;
								else continue;
							}
							else if (t == 'radio') {
								if (f.checked) v = f.value;
								else if (n in APP) continue;
							}
							else if (t == 'select-one' && f.selectedIndex > -1) {
								v = f.options[f.selectedIndex].value;
							}
							else if (t == 'select-multiple') {
								v = [];
								var options = f.options;
								for (var j=0; j<options.length; j++) {
									if (options[j].selected) {
										v.push(options[j].value);
									}
								}
							}
							APP[n] = v;
						}
					}
				}
				catch(e) {
					return false;
				}
				return APP;
			},
			/* checks if xpath applied on APP (form values as object) matches and returns boolean
			 * Fallback if xpath cannot be applied is always "false" so that effectively the validation is not done
			 * on the client but on the server only
			 */
			_shouldBeApplied: function(APP, boolOrXpath) {
				if (boolOrXpath === true || boolOrXpath == 'true()') {
					return true;
				}
				else {
					var exp = dpwn.pif.validation._xPath2expression(boolOrXpath);
					// TODO: cache expression?
					if (exp === false) return false; // xpath could no be converted
					try { // APP is used in exp so is needed!
						var r = eval(exp);
						return r;
					}
					catch(e) { // any error results in server side validation only
						return false
					}
				}
			},
			/*
			 * Main validation function that checks the different field types for valid input
			 *
			 * @form NODE-OBJECT Node Object of the <form> Element
			 */
			_doValidation: function(form) {
				// objectified form data
				var APP = dpwn.pif.validation._form2Object(form);
				var validation = dpwn.pif.models[form["PA.CONTEXT"].value].validation;
				var errors = {};

				for(var nodeName in validation) {
					var el = form[nodeName];
					if (!el) continue;
					var elType = dpwn.pif.util.getInputType(el);
					var valDef = validation[nodeName];
					// Skip elements that are marked as NOT relevant or the apply condition is not met
					if(valDef.relevant && dpwn.pif.validation._shouldBeApplied(APP, valDef.apply)) {
						// type val
						valDef.type = valDef.type.substring(valDef.type.indexOf(":")+1);
						if(valDef.type == "zipcode" && valDef.regexp == "") valDef.regexp = "__ZIPCODE__";
						if(valDef.type == "date" && valDef.regexp != "") valDef.regexp = "";

						if(elType == 'text' || elType == 'textarea' || elType == 'password') {
							if(el.value == '' && valDef.required) {
								errors[nodeName] = { type: "required" }
							} else if(el.value != '') {
								if(valDef.type == "double" || valDef.type == "integer") {
									_tmpValue = (valDef.type == "double") ? el.value.replace(/,/,".") : el.value;
									if(isNaN(_tmpValue) == false) {
										if(valDef.minvalue && _tmpValue < valDef.minvalue) {
											errors[nodeName] = { type: "minvalue" }
										} else if(valDef.maxvalue && currentValue > valDef.maxvalue) {
											errors[nodeName] = { type: "maxvalue" }
										}
									} else {
										errors[nodeName] = { type: "type" }
									}
								} else if(valDef.minlength && el.value.length < valDef.minlength) {
									errors[nodeName] = { type: "minlength" }
								} else if(valDef.maxlength && el.value.length > valDef.maxlength) {
									errors[nodeName] = { type: "maxlength" }
								} else if(valDef.regexp) { //The field is not empty, all other test were positive and there is a RegExp to check for valid input
									_tmpRegExp = valDef.regexp;
									if(_tmpRegExp.indexOf("/") != -1) {
										regExpStart = _tmpRegExp.indexOf("/");
										regExpEnd 	= _tmpRegExp.lastIndexOf("/")+1;
										_tmpRegExp = _tmpRegExp.substring(regExpStart,regExpEnd);
									}
									if(this.settings[_tmpRegExp]) _tmpRegExp = this.settings[_tmpRegExp];
									_tmpResult = (valDef.type == "email") ? this._checkEMail(el.value) : eval(_tmpRegExp + ".test(el.value)");
									if(!_tmpResult) errors[nodeName] = { type: "regexp" }
								}
							}
						} else if((elType == 'select-one' || elType == 'select-multiple') && el.value == '' && valDef.required) {
							errors[nodeName] = { type: "required" }
						} else if(elType == 'checkbox' && !el.checked && valDef.required) {
							errors[nodeName] = { type: "required" }
						} else if(elType == 'checkboxgroup' || elType == "radio" && valDef.required) {
							var found = false;
							for(var i=0; i<el.length; i++) {
								if(el[i].checked) {
									found = true;
									break;
								}
							}
							if(!found) errors[nodeName] = { type: "required" }
						}
					}
				}
				return errors;
			},
			/*
			 * Validates the entire form. Returns true if validation was successful.
			 *
			 * @form NODE-OBJECT Node Object of the <form> Element
			 * @simplyreturn: if true do not show wait message or do actions (used ba ajax.submit)
			 */
			validateForm: function(form, simplyreturn) {
				var formValid = true;
				var simplyreturn = simplyreturn || false;

				if(this.settings.doValidation) {
					var errors = this._doValidation(form);
					this._clearErrorOutput(form);
					if(dpwn.pif.util.propertyCount(errors) > 0) formValid = false;
				}
				if (formValid && simplyreturn) {
					return true;
				} else if(formValid) {
					if(form.target != "_blank") dpwn.pif.showWaitMessage();
					dpwn.pif.actions._submitActionDispatcher(form);
					return true;
				} else {
					this._writeErrorOutput(form, errors);
					return false;
				}
			},
			toggleMLHint: function(el, maxlen, inanycase) {
				var hint = $("#mlHint_" + el.id);
				var show = dpwn.pif.validation.updateMLHint(el, maxlen);
				if (inanycase || show) hint.show();
				else hint.toggle();
			},
			updateMLHint: function(el, maxlen) {
				var currentlen = el.value.length;
				var hint = $("#mlHint_" + el.id);
				if(currentlen <= maxlen) {
					$("strong", hint).html(maxlen - currentlen + '');
					if (maxlen - currentlen > 0) hint.children('.mlHintCut').remove();
					return false;
				} else {
					el.value = el.value.substr(0, maxlen);
					if (hint.children('.mlHintCut').length < 1) {
						hint.append('<p class="mlHintCut">' +
							dpwn.pif.messages.TEXT_TRUNCATED.replace('##maxlength##', maxlen) +
							'</p>');
					}
					$("strong", hint).html(0 + '');
					return true;
				}
			}
		},
		actions: {
			bindActions: function() {
				for(var context in dpwn.pif.models) { //Loop all objects in "_pif3_actions" object
					var actions = dpwn.pif.models[context].actions;
					var pagearea = ['menucontent', 'maincontent', 'crbs'];

					for (var i=0; i<pagearea.length; i++) {
						var application = $("*[@id='APP_CONTEXT_"+context+"_"+pagearea[i]+"']");
						if (application.html()) {
							var form = $('form', application)[0];
							if (form) {
								var formElements = form.elements;

								for(var eventID in actions.events) {
									var event = actions.events[eventID];
									var thisNode = formElements[event.nodeName];

									if(thisNode) {
										var thisInputType 	= dpwn.pif.util.getInputType(thisNode);
										var eventType 		= event.type;
										var eventDispatcher = event.dispatcher;

										if(eventType == "xforms-ready") {
											eventDispatcher.apply(thisNode);
										} else if(eventType == "xforms-value-changed") {
											if(thisInputType == "checkbox") {
												thisNode.onclick = eventDispatcher;
											} else if(thisInputType == "radio") {
												for(bARi=0;bARi<thisNode.length;bARi++) {
													thisNode[bARi].onclick = eventDispatcher;
												}
											} else {
												thisNode.onchange = eventDispatcher;
											}
										} else if(eventType == "DOMActivate") {
											if(thisInputType == "radio" || thisInputType == "checkboxgroup") {
												for(bARi=0;bARi<thisNode.length;bARi++) {
													thisNode[bARi].onclick = eventDispatcher;
												}
											} else {
												thisNode.onclick = eventDispatcher;
											}
										} else if(eventType == "keyup") {
											thisNode.onkeyup = eventDispatcher;
										} else if(eventType == "keydown") {
											thisNode.onkeydowndown = eventDispatcher;
										} else if(eventType == "xforms-submit") {
											actions.submitActions[actions.submitActions.length] = {
												"dispatcher" 		: eventDispatcher,
												"altSrcNodeName" 	: event.nodeName
											}
										}
									}
								}
							}
						}
					}
				}
			},
			_actionDispatcher: function(srcNode, eventID, altSrcNode) {
				var _COMMANDS = {
					'autocomplete': dpwn.pif.actions._autoComplete,
					'setdisplay': dpwn.pif.actions._setDisplay,
					'setrelevant': dpwn.pif.actions._setRelevant,
					'settarget': dpwn.pif.actions._setFormTarget,
					'setvalue': dpwn.pif.actions._setValue,
					'ajax_send': dpwn.pif.ajax.submit,
					'send': dpwn.pif.actions._submitForm
				}
				if(altSrcNode) srcNode = altSrcNode;
				var context = srcNode.form['PA.CONTEXT'].value;
				var event = dpwn.pif.models[context].actions.events[eventID];
				if(event.actions && event.actions.length > 0) { //Conditional
					if(srcNode.type == "checkbox") {
						for(var i=0; i<event.actions.length; i++) {
							checkboxChecked = srcNode.checked ? 'true' : 'false';
							if(event.actions[i].condition == checkboxChecked) {
								for(var j=0;j<event.actions[i].execute.length;j++) {
									var command = _COMMANDS[event.actions[i].execute[j].command]
									var params = event.actions[i].execute[j].params;
									command(srcNode, params[0], params[1])
								}
								break;
							} else {
								for(var j=0; j<event.default_action.length; j++) {
									var command = _COMMANDS[event.actions[i].execute[j].command]
									var params = event.actions[i].execute[j].params;
									command(srcNode, params[0], params[1])
								}
							}
						}
					} else {
						var nodeActionFound = false;
						for(var i=0; i<event.actions.length; i++) {
							if(event.actions[i].expression) {
								_tmpRegExp = event.actions[i].expression;

								if(_tmpRegExp.indexOf("/") != -1) {
									regExpStart = _tmpRegExp.indexOf("/");
									regExpEnd 	= _tmpRegExp.lastIndexOf("/")+1;
									_tmpRegExp = _tmpRegExp.substring(regExpStart,regExpEnd);
									event.actions[i].expression = _tmpRegExp;
								}
								_tmpResult = eval(_tmpRegExp + ".test(srcNode.value)");
								if(_tmpResult) {
									for(var j=0; j<event.actions[i].execute.length; j++) {
										var command = _COMMANDS[event.actions[i].execute[j].command]
										var params = event.actions[i].execute[j].params;
										command(srcNode, params[0], params[1])
									}
									nodeActionFound = true;
									break;
								}
							} else {
								if(event.actions[i].condition == srcNode.value) {
									for(var j=0; j<event.actions[i].execute.length; j++) {

										var command = _COMMANDS[event.actions[i].execute[j].command]
										var params = event.actions[i].execute[j].params;
										command(srcNode, params[0], params[1])
									}
									nodeActionFound = true;
									break;
								}
							}
						}
						if(!nodeActionFound) {
							for(var i=0; i<event.default_action.length; i++) {
								var command = _COMMANDS[event.default_action[i].command]
								var params = event.default_action[i].params;
								command(srcNode, params[0], params[1])
							}
						}
					}
				} else { //Regular
					for(var i=0; i<event.default_action.length; i++) {
						var command = _COMMANDS[event.default_action[i].command]
						var params = event.default_action[i].params;
						command(srcNode, params[0], params[1])
					}
				}
			},
			_submitActionDispatcher: function(form) {
				var context = form["PA.CONTEXT"].value;
				if(dpwn.pif.models[context].actions) {
					var submitActions = dpwn.pif.models[context].actions.submitActions;
					for(var i=0;i<submitActions.length;i++) {
						submitActions[i].dispatcher(null, form.elements[submitActions[i].altSrcNodeName]);
					}
				}
			},
			_autoComplete: function(srcNode, minChars, showMax) {
				var form = srcNode.form;
				$('#'+srcNode.id).autocomplete(//)Array(
					//["Aaa", "Aberdeen", "Ada", "Adamsville", "Addyston", "Adelphi", "Adena", "Adrian", "Akron"],
					dpwn.pif.ajax.DATA_SERVLET,
					{
						delay: 20,
						minChars: minChars || 3,
						cacheLength: 10,
						maxItemsToShow: showMax || 10,
						extraParams: {
							'PA.CONTEXT': form['PA.CONTEXT'].value,
							'PA.SERVERKEY': form['PA.SERVERKEY'].value,
							'PIF.SESSIONID': form['PIF.SESSIONID'].value,
							'PIF.APP_FORM': form['PIF.APP_FORM'].value,
							'PIF.AJAX_ACTION': 'autocomplete',
							'PIF.AJAX_NODESET': srcNode.name
							// query string will be added in autocomplete
						}
					}
				);
			},
			_setFormTarget: function(srcNode, value) {
				var form = srcNode.form;
				form.target = value;
				if(form.target == "_blank") dpwn.pif.hideWaitMessage();
			},
			/* group contains refs to fields and optional modules, value should be boolean */
			_setDisplay: function(srcNode, group, show) {
				$('.GROUP-'+group).each(function() {
					var f = $(this);
					if (show != f.is(':hidden')) return; // already targetstate
					var displayvalue;
					if (f.is('tr')) { // lines line in HTML table
						displayvalue = $.browser.msie ? 'block':'table-row';
					}
					else if (f.is('span')) {
						displayvalue = 'inline'; // single label/field
					}
					else {
						displayvalue = 'block';	// line in HTML div
					}
					if ($.browser.msie) {
						show ? f.css('display', displayvalue): f.css('display', 'none');
					} else {
						show ? f.animate({ height: "show" }, "slow", null, null, displayvalue):
						   f.animate({ opacity: "hide" }, "fast", null, null, displayvalue);
					}
				});
			},
			/* targets may be a list or a single item, value should be boolean */
			_setRelevant: function(srcNode, targets, value) {
				if (typeof targets == 'string') targets = [targets];
				var form = srcNode.form;
				var context = form["PA.CONTEXT"].value;
				for (var i=0; i<targets.length; i++) {
					var target = form[targets[i]];
					if(target) {
						var type = dpwn.pif.util.getInputType(target);
						if(type == "checkboxgroup" || type == "radio") {
							for(var j=0; j<target.length; j++) {
								target[j].disabled = !value;
								dpwn.pif.models[context].validation[targets[i]].relevant = value;
							}
						} else {
							target.disabled = !value;
							dpwn.pif.models[context].validation[targets[i]].relevant = value;
						}
					}
				}
			},
			_setValue: function(srcNode, targets, value) {
				if (typeof targets == 'string') targets = [targets];
				var form = srcNode.form;
				for (var i=0; i<targets.length; i++) {
					var target = form[targets[i]];
					if(target) {
						var type = dpwn.pif.util.getInputType(target);
						if(type == "text" || type == "textarea" || type == "password") {
							target.value = value;
						} else if (type == "checkbox" && typeof value == 'boolean') {
							target.checked = value;
						} else if (type == "radio" || type == "checkboxgroup") {
							for(j=0; j<target.length; j++) {
								if(target[j].value == value) {
									target[j].checked = true;
									break;
								}
							}
						} else if(type == "select-one" || type == "select-multiple") {
							for(j=0; j<target.options.length; j++) {
								if(target.options[j].value == value) {
									target.options[j].selected = true;
									break;
								}
							}
						}
					}
				}
			},
			_submitForm: function(srcNode,validate) {
				var form = srcNode.form;
				if(validate == 'true') {
					if(dpwn.pif.validation.validateForm(form)) {
						if(form.target != "_blank") dpwn.pif.showWaitMessage();
						form.submit();
					}
				} else {
					if(form.target != "_blank") dpwn.pif.showWaitMessage();
					dpwn.pif.actions._submitActionDispatcher(form);
					form.submit();
				}
			},
			_stepNaviSubmit: function(node) {
				var context 	= dpwn.util.getURLParam(node.href, "PA.CONTEXT");
				var app_mc 		= $('*[@id="APP_CONTEXT_'+context+'_maincontent"]/form');
				var validation	= (app_mc.attr("onsubmit") && ((''+app_mc.attr("onsubmit")).indexOf("validateForm") > -1)) ? "true" : "false";

				if(app_mc.size()) {
					var params = (node.href.indexOf("?") > -1 ) ? node.href.substr(node.href.indexOf("?")+1).split("&") : [];

					for(var i=0; i<params.length; i++) {
						if(params[i].indexOf("=") > -1) {
							var key_value = params[i].split("=");

							if($('input[@name="'+key_value[0]+'"]', app_mc).size()) {
								$('input[@name="'+key_value[0]+'"]', app_mc).attr('value', key_value[1]);
							} else {
								app_mc.prepend('<input name="'+key_value[0]+'" value="'+key_value[1]+'" type="hidden" />');
							}
						}
					}

					if($('input[@name="PIF.STEPNAVI_EXTENDED_SUBMIT"]', app_mc).size()) {
						$('input[@name="PIF.STEPNAVI_EXTENDED_SUBMIT"]', app_mc).attr('value', 'true');
					} else {
						app_mc.prepend('<input name="PIF.STEPNAVI_EXTENDED_SUBMIT" value="true" type="hidden" />');
					}

					dpwn.pif.actions._submitForm($("input[@name='PIF.NEXT_ACTIVITY']", app_mc).get(0), validation);
					return false;
				}
			}
		},
		redirect: function(redirectNameSrc, submission, url, redirectLink, context, serverKey) {
			dpwn.pif.showWaitMessage();

			var redirectName;

			if(redirectNameSrc != 'self') {
				field = document.getElementById(redirectNameSrc);

				if(field.type == 'select-one') {
					redirectName = field.options[field.selectedIndex].value;
				} else if(field.type == 'text') {
					redirectName = field.value;
				}
			} else {
				redirectName = submission;
			}

			var redirectURL = url + redirectLink + '?redirectName=' + redirectName + '&PA.CONTEXT=' + context + '&serverKey=' + serverKey;
			document.location = redirectURL;
		},
		showWaitMessage: function() {
			if ($("#pif3_please_wait").length == 0) {
				var wait = '<h1 id="pif3_please_wait">';
				wait += dpwn.pif.messages.PLEASE_WAIT;
				wait += '</h1>'
				$('.maincontent-area').prepend(wait);
			}
			try {
				$("#pif3_please_wait").fadeIn();
			}
			catch (e) {}
		},
		hideWaitMessage: function() {
			try {
				$("#pif3_please_wait").fadeOut();
			}
			catch (e) {}
		}
}
};

// General JS extensions
if(!Array().indexOf) {
	Array.prototype.indexOf = function(needle) {
		for(var i=0;i<this.length;i++) if(this[i] == needle) return i;
		return -1;
	}
}
var flashPluginVersion = 0;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if(plugin) {
	var words = navigator.plugins["Shockwave Flash"].description.split(" ");
	for (var i = 0; i < words.length; ++i) {
		if (isNaN(parseInt(words[i]))) continue;
		var flashPluginVersion = words[i];
	}
} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win") != -1)) {
	document.write(''+
		'<s'+'cript language="VBScript">\n'+
		'	on error resume next\n'+
		'	ver=0\n'+
		'	For flash_i=7 to 3 step -1\n'+
		'		Set x = CreateObject("ShockwaveFlash.ShockwaveFlash." & flash_i)\n'+
		'		v = IsObject(x)\n'+
		'		If v Then\n'+
		'			flashPluginVersion = flash_i\n'+
		'			Exit For\n'+
		'		End If\n'+
		'	Next\n'+
		'</scrip'+'t>');
}
function flashOK(version) {
	return (flashPluginVersion >= version)? true : false;
}

/*
 * Kept for backwards compatibility
 * @call may be a function string or function object
 */
function globalOnLoad() { /* backwards compat stub */ }
function addOnLoad(call) { dpwn.page.load(call); }
function addOnUnLoad(call) { dpwn.page.unload(call); }
function popup(url, winBreite, winHoehe, posLinks, posTop, NOTUSED, options, winname) { dpwn.page.popup(url, winBreite, winHoehe, posLinks, posTop, NOTUSED, options, winname); }
function setFlashVar(flashid,variable,value) { dpwn.page.misc.setFlashVar(flashid,variable,value); }

/* run for all clients */
dpwn.page.ready([
	dpwn.page.modules.prepareLabelPopup,
	function() {
		$('.flashcontainer>object').each(function(){
			dpwn.page.misc.setFlashVar($(this).attr("id"),"startTracking","true");
		});
		$('.flashcontainer>embed').each(function(){
			dpwn.page.misc.setFlashVar($(this).attr("id"),"startTracking","true");
		});
	}
])

$(window).load(dpwn.page._execLoadCalls);
$(window).unload(dpwn.page._execUnloadCalls);
// called by wcms body/@onload  as this does not work in IE6
function wcmsonload() {
	dpwn.page._execLoadCalls()
}
