// #############################################################
//
//	IS24 Scripts
//
// #############################################################

/**
 * -------------------------------------------------------------
 * Init global vars
 * -------------------------------------------------------------
 *
 *
*/
// Determine crucial browsers according to its user agent
//
// get browser
var is24_useragent = navigator.userAgent.toLowerCase();
//
var is24_isIE     = is24_useragent.indexOf("msie") != -1 && is24_useragent.indexOf("opera") == -1 ? true : false;
var is24_isIE5    = is24_useragent.indexOf("msie 5") != -1 && is24_useragent.indexOf("opera") == -1 ? true : false;
var is24_isOpera  = is24_useragent.indexOf("opera") != -1 ? true : false;
var is24_isSafari = is24_useragent.indexOf("safari") != -1 ? true : false;
//
// temporarily store a certain single form value
var is24_formValueBuffer = "";
//
// store values of highlighted form fields in a global array (using tab to enter and leave fields with pre-filled text)
// is24_formFieldValues[0] created as first element to have some sort of hash map behaviour
// var is24_formFieldValues = new Array();
// is24_formFieldValues[0] = new Array();

// new initial function call, when page ready
if(typeof YAHOO!="undefined") {
	YAHOO.util.Event.onDOMReady(is24_executeOnLoad); 
}
 else {
	if(is24_isIE) {
					window.attachEvent('onload', is24_executeOnLoad); // IE event model
				}
				else {
					window.addEventListener("load", is24_executeOnLoad , false); // dom2 bubble event
				}	
	}			

// test: dont activate help div if no request is made
	if(is24_isIE) {
					window.attachEvent('onload', createMapHelper); 
				}
				else {
					window.addEventListener("load", createMapHelper, false); 
				}


/**
 * ---------------------------------------------------------------
 * Generic getter for markup elements called by its css class name
 * ---------------------------------------------------------------
 *
 * Usage examples of how to call the function:
 *
 * To get all a elements in the document with a "is24-info" class:
 * getElementsByClassName(document, "a", "is24-info");
 *
 * To get all div elements within the element named "container", with a "is24-col" and a "is24-left" class:
 * getElementsByClassName(document.getElementById("container"), "div", ["is24-col", "is24-left"]);
 *
*/

function getElementsByClassName (oClassNames, strTagName, oElm){
	// Yahoo method replaces old implementation
	return YAHOO.util.Dom.getElementsByClassName(oClassNames, strTagName, oElm);
};

// Array support for the push method in IE 5
if (typeof Array.prototype.push != "function") {
	Array.prototype.push = ArrayPush;
	function ArrayPush (_value) {
		this[this.length] = _value;
	}
};

/**
 * -------------------------------------------------------------
 * Externalise links
 * -------------------------------------------------------------
 *
 * Method to spare the target attribute in anchors due to BITV.
 * This is a way to have the same function another way around.
*/

function is24_externaliseLinks() {
//	try{
//		console.info("methode externaliseLinks ausgeführt.");	
//	}catch(error){}
	if (!document.getElementsByTagName) return; // if dom not ready or what?
	var anchors = document.getElementsByTagName("a"); 
	for (var i=0; i<anchors.length; i++) { 
		var anchor = anchors[i]; 
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank"; 
		}
	} 
};


/**
 * -------------------------------------------------------------
 * Open Popup Script
 * -------------------------------------------------------------
 *
 * Opens a new window based on parameters given to this function.
 * Alternatively, the link opens in a seperate window in case that
 * Javascript is not available (through target="_blank" in href tag).
 *
 * @param String linkURL Link address to be displayed in the popup window
 * @param String winName Name of the particular popup window
 * @param int winWidth Width of the popup window
 * @param int winheight Height of the popup window
 * @param String winArgs Properties of the popup window
 * @param bool setfocus Set to true in order to focus the popup window
 *
 * @return false
 *
*/

function openPopup(linkURL,winName,winWidth,winHeight,winArgs,setfocus) {
	if (linkURL != null) {
		if (window.is24_isPopup == null) {
			if (winName == null) {
				winName = "is24_newWin";
			}
			if (winWidth == null || typeof winWidth != "number") {
				winWidth = 600;
			}
			if (winHeight == null || typeof winHeight != "number") {
				winHeight = 400;
			}
			if (winArgs == null) {
				winArgs = "";
			}
			if (setfocus == null) {
				setfocus = true;
			}
			//
			// List of possible properties in the arguments variable, seperated by a comma, no leading/trailing spaces!
			//
			//   location	= yes|no 	|	top		= [pixel]
			//   menubar	= yes|no	|	left	= [pixel]
			//   resizable	= yes|no	|	screenX	= [pixel]
			//   status		= yes|no	|	screenY	= [pixel]
			//   titlebar	= yes|no
			//
			// Example link:
			//
			// <a href="http://www.is24.de" onclick="return openPopup(this.href,'newWin',800,600,'location=no,menubar=yes,titlebar=no')" target="_blank" title="Externer Link">Text des Links</a> 
			//
			// todo #15662
			var scrollVar = ",scrollbars=yes";
			if(winArgs.indexOf("scrollbars=") != -1){
				scrollVar = "";
				var reg = /scrollbars=(0|no)/;
				winArgs = winArgs.replace(reg,"scrollbars=yes");
			}
			_winArgs = "width="+ winWidth +",height="+ winHeight + ", " + winArgs + scrollVar;
			var _newWin = window.open(linkURL,winName,_winArgs);
			if (setfocus == true) {
				_newWin.focus();
			}
		} else {
			// Link shall open in an already opened popup
			document.location.href = linkURL;
		}
		return false;
	}
	return false;
};
// end openPopup()



/**
 * -------------------------------------------------------------
 * Switch Tabs at homepage - updated with YAHOO library!
 * -------------------------------------------------------------
 *
 * Switches between 2 tabs on the content area
 *
 * @param int num Number of tab to switch to
 *
*/
// deprecated!
function switchToTab(num) {
//	try{
//		console.info("methode switchToTab ausgeführt.");	
//	}catch(error){}
		if (num != null) {
			var inactive;
			var tab2switchon;
			var tab2switchoff;
			var _useragent = navigator.userAgent.toLowerCase();
			if (num == 1) {
				inactive = 2;
				tab2switchon = num;
				tab2switchoff = 2;
			} else if (num == 2) {
				inactive = 1;
				tab2switchon = num;
				tab2switchoff = 1;
			}
				// Set inactive button
				YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("tab0"+ tab2switchoff),"backgroundColor","#fc9");
				YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("switchlink"+ tab2switchoff), "color", "#006");
				//document.getElementById("tab0"+ tab2switchoff).style.backgroundColor = "#fc9";
				//document.getElementById("switchlink"+ tab2switchoff).style.color = "#006";
				// Set active button
				YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("tab0"+ tab2switchon),"backgroundColor", "#f60");
				YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("switchlink"+ tab2switchon), "color", "#fff");
			
			// Switch tabs
			YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("tab"+ tab2switchoff), "display", "none");
			YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("tab"+ tab2switchon), "display", "block");
		}   
}; // end switchToTab()


/**
 * -------------------------------------------------------------
 * Switch between 2 Tabs - updated with YAHOO library
 * -------------------------------------------------------------
 *
 * Special Case
 *
*/
// deprecated
function is24_activateTab(num) {
//	try{
//		console.info("methode activateTab leer ausgeführt.");	
//	}catch(error){}
	var _activetab = num == 1 ? 1 : 2;
	var _previoustab = num == 1 ? 2 : 1;
	//document.getElementById("is24-tab"+ _activetab).className = "is24-tab-active";
	//document.getElementById("is24-tab"+ _previoustab).className = "";
	YAHOO.util.Dom.replaceClass(YAHOO.util.Dom.get("tab"+ tab2switchoff), "", "is24-tab-active");
	YAHOO.util.Dom.replaceClass(YAHOO.util.Dom.get("tab"+ tab2switchoff), "is24-tab-active", "");
	YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("is24-switchtext"+ _activetab),"display", "block");
	YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get("is24-switchtext"+ _previoustab),"display", "none");   
};
// deprecated
function is24_switchTabs() {
//	try{
//		console.info("methode switchTabs leer ausgeführt.");	
//	}catch(error){}
	//if (document.getElementById && document.getElementsByTagName) {
		if ( YAHOO.util.Dom.get("is24-tab1") && YAHOO.util.Dom.get("is24-tab2") ) {
			try{
				console.info("tabs werden behandelt.");	
			}catch(error){}
			var _tab1 = YAHOO.util.Dom.get("is24-tab1");
			var _tab2 = YAHOO.util.Dom.get("is24-tab2");
			_arrlinks1 = _tab1.getElementsByTagName("A");
			_link1 = _arrlinks1[0];
			_arrlinks2 = _tab2.getElementsByTagName("A");
			_link2 = _arrlinks2[0];
			_link1.onclick = function() {
				is24_activateTab(1);
				return false;
			}
			_link2.onclick = function() {
				is24_activateTab(2);
				return false;
			}
		}    
	//} 
};



/**
 * -------------------------------------------------------------
 * Resize <select> fields in forms - workaround for 
 * missing min-width css attribute in IE - updated with YAHOO library
 * -------------------------------------------------------------
 *
 * Take all select fields (in div#is24-content only)
 * and resize them if narrower than 70px
 *
*/
function is24_resizeSelectFields() {
//	try{
//		console.info("methode resizeSelectFields ausgeführt.");	
//	}catch(error){}
	if (document.getElementsByTagName) {
		var contentbox = YAHOO.util.Dom.get("is24-content");
		if (contentbox) {
			var dropdowns  = contentbox.getElementsByTagName("select");
			for (var i=0; i<dropdowns.length; i++) {
				if (dropdowns[i].clientWidth < (70)) {
					YAHOO.util.Dom.setStyle(dropdowns[i], "width", "70px");
				}
			}
		}
	}
}; // end is24_resizeSelectFields()



/**
 * --------------------------------------------------------------------------
 * Funtions highlighting form element rows, handling pre-filled text etc.
 * --------------------------------------------------------------------------
 *
 *
*/

// Select row in form - YAHOO enhanced
function is24_selectElement(element) {
//	try{
//		console.info("Methode is24_selectElement ausgeführt.");	
//	}catch(error){}
	
	var _parentNode;
	if ( element.tagName != "AREA" ) {
		_parentNode = element.parentNode.parentNode;		 // Target DOM node we want to be highlighted
	} else {
		_parentNode = element.parentNode.parentNode.parentNode;
	}
	YAHOO.util.Dom.addClass(_parentNode,"is24-selectedelement");
};
//
// Unselect formerly selected form row - YAHOO enhanced
function is24_unselectElement( element ) {
//	try{
//		console.info("Methode is24_UNselectElement ausgeführt.");	
//	}catch(error){}
		
	if ( element.tagName != "AREA" ) {
		_parentNode = element.parentNode.parentNode;		 // Target DOM node we want to be highlighted
	} else {
		_parentNode = element.parentNode.parentNode.parentNode;
	}
	YAHOO.util.Dom.removeClass(_parentNode,"is24-selectedelement");
}

// no YAHOO necessary
// Set event handler for form input fields on page load and perform select/unselect form row
function is24_setEventHandler(){
	var _paramAttribute = "";
	var _arrNodes = "";
	var _loopArray = new Array();
	var _currentPNode = "";
	var _styleClass = "is24-formtype-selectedrow"; // this class attribute will be create by a TR-tag
	
	if (!is24_isIE) {
		_paramAttribute = "class";
	} else {
		_paramAttribute = "className";
	}

	_arrNodes = document.getElementsByTagName("INPUT");
	_loopArray[0] = _arrNodes;
	_arrNodes = document.getElementsByTagName("TEXTAREA");
	_loopArray[1] = _arrNodes;	
	_arrNodes = document.getElementsByTagName("SELECT");
	_loopArray[2] = _arrNodes;	
	_arrNodes = document.getElementsByTagName("AREA");
	_loopArray[3] = _arrNodes;

	for ( var j=0; j != _loopArray.length; j++ ) {
		_arrNodes = _loopArray[j];
		for ( var i=0; i != _arrNodes.length; i++ ) {
			if (_arrNodes[i].parentNode.parentNode.parentNode.tagName == "TBODY") {
				if (_arrNodes[i].getAttribute(_paramAttribute, "false") != "is24-noscript" ) { 
					// create and set the attribute				
					var cssClass = document.createAttribute("class");
					cssClass.nodeValue = _styleClass;
					_arrNodes[i].parentNode.parentNode.setAttributeNode(cssClass);
				}				
			}	 
			// input of type "HIDDEN" will be excluded from event handling 
			if( _arrNodes[i].type != "hidden") {			
				if (_arrNodes[i].tagName == "AREA") {
					_currentPNode = _arrNodes[i].parentNode.parentNode.parentNode;
				} else if(_arrNodes[i].tagName == "INPUT" && _arrNodes[i].parentNode.parentNode.tagName == "LI") {
					_currentPNode = _arrNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode;
				} else {
					_currentPNode = _arrNodes[i].parentNode.parentNode;					
				}				
				// check class name for null
				if ( _currentPNode.getAttribute(_paramAttribute, "false") != null) {
					// check for form type					
					if ( _currentPNode.getAttribute(_paramAttribute, "false").indexOf("is24-formtype") != -1) {					
						// check for class definition
						if ( _currentPNode.getAttribute(_paramAttribute, "false") != null){
							// exclude input fields with class name "is24-noscript"
							if ( _currentPNode.getAttribute(_paramAttribute, "false").indexOf("is24-noscript") == -1 ) { 
								_arrNodes[i].onfocus = function() {
									is24_selectElement(this); 
								}
								_arrNodes[i].onblur  = function() { 
									is24_unselectElement(this); 
								}
							}
						}
					}				
				}
			}
		}	
	}
} // end select row in form 




/**
 * -------------------------------------------------------------------------
 * Script for print layer in result list
 * -------------------------------------------------------------------------
 * IE only
 *
*/

function is24_addMouseoverFunctionToPrintLayer() {
//	try{
//		console.info("Methode is24_addMouseOverFunctionToPrintLayer ausgeführt.");	
//	}catch(error){}
	var _targetcontainer;
	var is24_printlayerTimeout;
	if (getElementsByClassName && is24_isIE) {
		//
		//check for print container
		var node = document.getElementsByTagName("body")[0];
		var _element = getElementsByClassName("is24-print", "div", node);
		//seek element (if we have one) and style it
		if ((typeof _element != "undefined") && _element.length > 0) {
			_targetcontainer = _element[0];
			//
			//DOM crawling
			var _targetlist1 = _targetcontainer.childNodes[0];	// First occurring <ul> ...
			var _targethref = _targetlist1.childNodes[0];		// ... sibling href next to it ...
			var _targetlist2 = _targethref.childNodes[2];		// ... and finally the target <ul>.
			//
			//assign styles for target list
			//_targetlist2.style.position = "absolute";
			//_targetlist2.style.top = "15px";
			//_targetlist2.style.left = "-223px";
			//_targetlist2.style.display = "none";
			//_targetlist2.style.backgroundImage = "url("+ _pathprefix +"/local/cms/is24/img/bg_drucken_komplett.gif)";
			//_targetlist2.style.backgroundRepeat = "no-repeat";

			YAHOO.util.Dom.setStyle(_targetlist2, "position", "absolute");
			YAHOO.util.Dom.setStyle(_targetlist2, "top", "15px");
			YAHOO.util.Dom.setStyle(_targetlist2, "left", "-223px");
			YAHOO.util.Dom.setStyle(_targetlist2, "display", "none");
			YAHOO.util.Dom.setStyle(_targetlist2, "backgroundImage", "url(/local/cms/is24/img/bg_drucken_komplett.gif)");
			YAHOO.util.Dom.setStyle(_targetlist2, "backgroundRepeat", "no-repeat");

			//now assign events but with setTimeout(). otherwise we get this flickering behaviour
			for (i=0; i < _targetcontainer.childNodes.length; i++) {
				_targetcontainer.childNodes[i].onmouseover = function() {
					YAHOO.util.Dom.setStyle(_targetlist2, "display", "block");
					clearTimeout(is24_printlayerTimeout);
				}
				_targetcontainer.onmouseout = function() {
				_obj = _targetlist2;
				is24_printlayerTimeout = setTimeout("is24_setObjectInvisible(_obj)", 100);
				}
			}
		}
	}
};
//
//external helper function - updated with YAHOO library
function is24_setObjectInvisible(obj) {
	YAHOO.util.Dom.setStyle(obj,"display","none");
}





/**
 * -------------------------------------------------------------------------
 * Select all checkboxes/radio input fields and set width to auto (CSS fix)
 * -------------------------------------------------------------------------
 * updated with YAHOO library
 *
*/
function is24_resetWidthCssFix() {
//	try{
//		console.info("methode resetWidthCssFix ausgeführt.");	
//	}catch(error){}
	if (document.getElementsByTagName) {
		//var _forms = document.getElementsByTagName("FORM");
		var _inputfields;
		//for (i=0; i < _forms.length; i++) {
			//if (_forms[i].className == "is24-form") {
				_inputfields = document.getElementsByTagName("INPUT");
				for (j=0; j < _inputfields.length; j++) {
					if (_inputfields[j].type == "checkbox" || _inputfields[j].type == "radio") {
						YAHOO.util.Dom.setStyle(_inputfields[j],"width","auto");
						//_inputfields[j].style.border = "0 none";	/* IE secure fix */
					}
					if (_inputfields[j].type == "submit" || _inputfields[j].type == "reset" || _inputfields[j].type == "button") {
						YAHOO.util.Dom.setStyle(_inputfields[j],"textAlign","center");
						YAHOO.util.Dom.setStyle(_inputfields[j],"height","20px");
					}
				}
			//}
		//}
	}
}; // end is24_resetWidthCssFix()




/**
 * -------------------------------------------------------------------------
 * Select all <td> and set vertical alignment to given html attribute value
 * Note: terms legacy fix
 * -------------------------------------------------------------------------
 * updated with YAHOO library
 *
*/
function is24_setMagicElementStyles() {
//	try{
//		console.info("methode setMagicElementStyles ausgeführt.");	
//	}catch(error){}
	if (document.getElementsByTagName) {
		var _boxes = document.getElementsByTagName("DIV");
		var _fonts = document.getElementsByTagName("FONT");
		var _tables = document.getElementsByTagName("TABLE");
		//set table cell styles 
		for (i=0; i < _boxes.length; i++) {
			if (YAHOO.util.Dom.hasClass(_boxes[i], "termslegacy")) {
				_tablecells = _boxes[i].getElementsByTagName("TD");
				for (j=0; j < _tablecells.length; j++) {
					// some legacy code style fixes 
					if (_tablecells[j].getAttribute("valign") == "top") {
						/* if we already have a css class, then concat new one - else create one  
						if ( _tablecells[j].className ) {
							_tablecells[j].className = _tablecells[j].className + " is24-aligntop";
						} else {
							_tablecells[j].className = "is24-aligntop";
						} */
						YAHOO.util.Dom.addClass(_tablecells[j], "is24-aligntop");
					}
					if (_tablecells[j].getAttribute("align") == "center") {
						// _tablecells[j].style.textAlign = "center";
						YAHOO.util.Dom.setStyle(_tablecells[j], "textAlign", "center");
					}
				}
			}
		}
		//rewrite <font> tag colors 
		for (k=0; k < _fonts.length; k++) {
			if (_fonts[k].getAttribute("color") == "#d9e1f0") {
				_fonts[k].setAttribute( "color", "#ff6600", 0 );
			}
		}
		//set hard styles table widths to 100% via style property
		for (m=0; m < _tables.length; m++) {
			if (_tables[m].getAttribute("width") == "100%") {
				// _tables[m].style.width = "100%";
				YAHOO.util.Dom.setStyle(_tables[m], "width", "100%");
			}
		}
	}
}; // end is24_setMagicElementStyles()




/**
 * -------------------------------------------------------------
 * Implements js code for imageMapHighlighting from cgix1
 * -------------------------------------------------------------
 *
 *
*/
function showKarte( imgName ) {
	if (document.getElementById) {
		document.getElementById('karte').src = "/published-images/" + imgName;
	}
};


/**
 * -------------------------------------------------------------
 * Embed visual mouseover behaviour in subnavigation 
 * (due to .htc replacement)
 * -------------------------------------------------------------
 * updated with Yahoo library
 *
*/
function is24_setSubnavigationMouseovers() {
//	try{
//		console.info("methode setSubnavigationMouseovers ausgeführt.");	
//	}catch(error){}
	if (is24_isIE) {
		//vars
		var _leftnav, _rightnav;
		var _leftlistitems, _rightlistitems;
		var _leftlinks, _rightlinks;
		//
		//add a path prefix in case we're testing locally - deprecated, no 'relaunch' folder anymore!
		var _pathprefix = "";
		/*if (document.location.href.indexOf("localhost") != -1 || document.location.href.indexOf("10.0.") != -1) {
			// _pathprefix = "/is24_relaunch";
		}*/
		//
		if (document.getElementById && document.getElementsByTagName) {
			//
			//Start preparing left subnavigation ...
			if (document.getElementById("is24-subnav-left")) {
				_leftnav = YAHOO.util.Dom.get("is24-subnav-left");
				_leftlistitems = _leftnav.getElementsByTagName("LI");
				for (var i=0; i < _leftlistitems.length; i++) {
					if (!YAHOO.util.Dom.hasClass(_leftlistitems[i],"is24-active")) {
						_leftlistitems[i].onmouseover = function() {
							this.style.background = "url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_subnavleft_left.gif) no-repeat";
							if (this.className.indexOf("is24-firstelement") != -1) {
								this.style.marginLeft = "0";
								this.style.paddingLeft = "0";
							} else {
								this.style.marginLeft = "-1px";
								this.style.paddingLeft = "1px";
							}
							_anchor = this.childNodes[0];
							_anchor.style.background = "url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_subnavleft_right.gif) right top no-repeat";
							_anchor.style.color = "#006";
							_anchor.style.textDecoration = "underline";
						};
						_leftlistitems[i].onmouseout = function() {
							if (this.className.indexOf("is24-lastelement") != -1) {
								this.style.background = "none";
							} else {
								this.style.background = "#f60 url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_borderitem.gif) right top no-repeat";
							}
							this.style.marginLeft = "0";
							this.style.paddingLeft = "0";
							_anchor = this.childNodes[0];
							_anchor.style.background = "none";
							_anchor.style.color = "#fff";
							_anchor.style.textDecoration = "none";
						}
					}
				}			
			}
			//
			//... and now for the right subnavigation.
			if (document.getElementById("is24-subnav-right")) {
				_rightnav = YAHOO.util.Dom.get("is24-subnav-right");
				_rightlistitems = _rightnav.getElementsByTagName("LI");
				for (var j=0; j < _rightlistitems.length; j++) {
					if (!YAHOO.util.Dom.hasClass(_rightlistitems[j],"is24-active")) {
						_rightlistitems[j].onmouseover = function() {
							this.style.background = "url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_subnavleft_left.gif) no-repeat";
							_anchor = this.childNodes[0];
							_anchor.style.background = "url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_subnavleft_right.gif) right top no-repeat";
							_anchor.style.color = "#006";
							_anchor.style.textDecoration = "underline";
						}
						_rightlistitems[j].onmouseout = function() {
						if (this.className.indexOf("is24-firstelement") != -1) {
							this.style.background = "url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_subnavright_left.gif) 0 2px no-repeat";
						} else {
							this.style.background = "none";
						}
						_anchor = this.childNodes[0];
						if (this.className.indexOf("is24-firstelement") != -1) {
							_anchor.style.background = "url("+ _pathprefix +"/local/cms/is24/img/subnav/bg_subnavright_right.gif) right 2px no-repeat";
							_anchor.style.color = "#006";
							
						} else {
							_anchor.style.background = "none";
							_anchor.style.color = "#fff";
						}
						_anchor.style.textDecoration = "none";
					}
					}
				}			
			}
		}
	}
} // end is24_setSubnavigationMouseovers()


// Author: Frank Berlin 27-07-2007
// Looks over all forms in the document, that have the "js_reqired" class and changes the onsubmit event of these forms
// so that later the forms are checked for input on submitting the form.
// Forms without the CSS class are not affected in any way.
function is24_prepareForms() {
	var formulare = document.getElementsByTagName("form");
	for(var i = 0; i < formulare.length; i++) {
		var input = formulare[i].getElementsByTagName("input");
		for(var a = 0; a < input.length; a++) {
			if ( input[a].className.indexOf("js_required") != -1){
				//formulare[i].setAttribute("defAction", formulare[i].action); // try other way of attaching attribute
				formulare[i].onsubmit = function(event){
					var formular = this; // reference to current form
					var input = formular.getElementsByTagName("input");
					for(var i = 0; i < input.length; i++) {
						if ( YAHOO.util.Dom.hasClass(input[i],"js_required") && input[i].value == ""){
							alert("Bitte füllen Sie alle Felder aus!");
							return false;
						}
					}
					//formular.action = "http://hausratversicherung.financescout24.de/HR/index.aspx"; // TODO: generische Lösung suchen!! wenn formular auf post umgestellt wurde, dann kann diese zeile hier raus
					return true;	
				} // end function 
				;
				
				break; // attach submit handler only once!
			}
		}
	}
}

/**
 * -------------------------------------------------------------
 * # Collect all functions needed to be executed on page load #
 * -------------------------------------------------------------
 *
 * Note: Currently in use!
 *
*/
function is24_executeOnLoad() {
	is24_externaliseLinks();
	is24_resizeSelectFields();
	is24_setEventHandler();
	is24_resetWidthCssFix();
	is24_setMagicElementStyles();
	is24_addMouseoverFunctionToPrintLayer();
	is24_setSubnavigationMouseovers();
	//is24_switchTabs();
	is24_prepareForms(); 			// looks for forms that have the js_required attribute and gives them an onsubmit event
	locateCalendar(); 				// Dokument durchsuchen nach links zum kalenderwidget
//	is24_createHelpDivElement();    // happens onload because of IE bug	
//	is24_setMouseOverForMapButtons();
//	is24_setStyleForFirstTermsHeadline();
	repaireMalformedCookies(); // Clear host cookies and replace them with domain cookies. Remove it after 1.5.2009.
//	createMapHelper(); // create help div for expose map layer 
};

/**
 * -------------------------------------------------------------
 * Helpers
 * -------------------------------------------------------------
 *
*/

// Resize window - but only if user didn't manually change window size
function resizeWindow( _width,_height ) {
	if ( _width == null ) {
		_width = 600;
	}
	if ( _height == null ) {
		_height = 400;
	}
	var doresize = false;
	var navagent = navigator.userAgent;
	var isIE = navagent.indexOf("MSIE") != -1 ? true : false;
	if ( isIE ) {
		if ( (document.body.offsetHeight + 73) < _height || document.body.offsetWidth < _width ) {
			doresize = true;
		}
	} else {
		if ( window.outerHeight < _height || window.outerWidth < _width ) {
			doresize = true;
		}
	}
	if ( doresize ) {
		top.resizeTo( _width,_height );
	}
};

function setStatus(msg) {
	window.status = msg;
	return true;
};

function clearStatus() {
	window.status = "";
	return true;
};

// Set form buttons from disabled to enabled - updated with Yahoo library
function unlockSubmitButton(strId){
	var _obj;
	if (document.getElementById) {
		_obj = YAHOO.util.Dom.get(strId);
		_obj.disabled = false;
	}
};


/**
 * -------------------------------------------------------------
 * Select/unselect all checkboxes (only within MyScout result list) 
 * -------------------------------------------------------------
 *
*/

function select_all_checkboxes( formName, checkboxName ) {
	var isCheckAllButtonChecked = 0;
	var checkbox_value="";
	if (formName == undefined) {
		formName = "simbamain";
	}
	if (checkboxName == undefined) {
		checkboxName = "complexPager.resultList";
	}
	//alert( "forName = " + formName + " checkboxName = " + checkboxName );
	for (ix = 0; ix < document.forms[formName].length; ix++) {
		checkbox_value=document.forms[formName].elements[ix].name;
		if (document.forms[formName].alle_markierenSuchfunktionen.value == "Alle markieren") {
			if (checkbox_value.substring(0,23)==checkboxName) {
				document.forms[formName].elements[ix].checked = true;
				isCheckAllButtonChecked = 1;
			}
		} else {
			if (checkbox_value.substring(0,23)==checkboxName) {
				document.forms[formName].elements[ix].checked = false;
				isCheckAllButtonChecked = 0;
			}
		}
	}
	if (isCheckAllButtonChecked == 1) {
		document.forms[formName].alle_markierenSuchfunktionen.value = "Alle deaktivieren";
	} else {
		document.forms[formName].alle_markierenSuchfunktionen.value = "Alle markieren";
	}
};



/**
 * -------------------------------------------------------------
 * Help Popup: layer with help text which follows mouse cursor
 * -------------------------------------------------------------
 *
 *
*/

var is24_elemHelp = "null";
var is24_elemHelpCSSID = "is24-helper-popup-layer";
var is24_elemHelpCSSCLASS = "is24-popup-help-element"; // question: is this even used????

// TODO use images instead of url
var is24_img_hover_in  = "/local/cms/is24/icn/icon_info_1.gif";
var is24_img_hover_out = "/local/cms/is24/icn/icn_info.gif";

var is24_x_pos = "0";
var is24_y_pos = "0";

function createMapHelper(){
	/* div elem for map popup layer */
	var is24_elemMap = document.createElement("div");
	is24_elemMap.setAttribute("id", "is24-map-helper-layer");
	document.body.appendChild(is24_elemMap);
}

function is24_createHelpDivElement() {			
		var bodyElem = document.getElementsByTagName("body")[0];
		is24_elemHelp = document.createElement("div");
		is24_elemHelp.setAttribute("id", is24_elemHelpCSSID);
		is24_elemHelp.style.width = "195px";
		is24_elemHelp.style.zIndex = 100;
		bodyElem.appendChild(is24_elemHelp);
		// bugfix - hiding select boxes under an iframe
		if(document.all){
			hideBox = document.createElement("iFrame");
			hideBox.style.scrolling = "no";
			hideBox.style.background = "white";
			// #20491
			hideBox.src = "/local/cms/is24/js/scwblank.htm"; // safe page for iframe
			hideBox.style.width = "180px";
			hideBox.style.position = "absolute";
			hideBox.style.zIndex = 95;
			hideBox.style.visibility = "hidden";
			bodyElem.appendChild(hideBox);
		}
};

function is24_updateXYPosition(e) {
	//is24_x_pos = (document.all) ? window.event.x : e.clientX + document.body.scrollLeft;
	//is24_y_pos = (document.all) ? window.event.y : e.clientY + document.body.scrollTop;	
	is24_x_pos = YAHOO.util.Dom.getX(e); // + document.body.scrollLeft;
	is24_y_pos = YAHOO.util.Dom.getY(e); // + document.body.scrollTop;
};

function is24_helpHoverOut(obj) {
	obj.src = is24_img_hover_out;
	window.setTimeout("is24_hideDelay()", 200);
};

function is24_showDelay() {
	is24_elemHelp.style.visibility = "visible";
	if(typeof hideBox != "undefined") hideBox.style.visibility = "visible";
};

function is24_hideDelay() {
	is24_elemHelp.style.visibility = "hidden";
	if(typeof hideBox != "undefined") hideBox.style.visibility = "hidden";
};

// almost no YAHOO functions here, because of error in IE!
function is24_helpHover(obj, txt, hoverimg) {
	if(typeof is24_elemHelp != "object") is24_createHelpDivElement(); // test: create help div, if not already there
	is24_updateXYPosition(obj); // get position of the hovered help-icon
	is24_img_hover_out = obj.src;
	is24_img_hover_in = hoverimg;
	obj.src = is24_img_hover_in;
	var breite = (window.innerWidth) ? window.innerWidth : document.body.offsetWidth;
	if(is24_elemHelp != "null") {		
		is24_elemHelp.innerHTML = "<div class=\"is24-help-outer\"><div class=\"is24-help-inner\"><p>"+txt+"</div></div>";
		if(is24_x_pos+(parseFloat(is24_elemHelp.style.width)) >= breite) {
			// zu weit draussen, help element wird nach links verschoben
			var differ = (breite - 5 - (parseFloat(is24_elemHelp.style.width)+ is24_x_pos));
			is24_elemHelp.style.left = is24_x_pos + differ + "px";
		} 
		else {
			// innerhalb des schirms
			is24_elemHelp.style.left = is24_x_pos+10+"px";
		}
		// y position ändert sich nicht
		is24_elemHelp.style.top = is24_y_pos+10+"px";
		// hideBox for IE
			if(typeof hideBox != "undefined"){
				hideBox.style.top = parseInt(is24_elemHelp.style.top)+5+"px";
				hideBox.style.left = parseInt(is24_elemHelp.style.left)+11+"px";
				hideBox.style.width = "180px";
				var helpHeight = YAHOO.util.Dom.getElementsByClassName("is24-help-inner", "div");
				hideBox.style.height = helpHeight[0].offsetHeight-20+"px"; // todo: correct height
			}
		window.setTimeout("is24_showDelay()", 200);
		
	}
};
// concept function for animating fade-ins
function fadeIn(elem){
	// half second fade in 
	elem.style.opacity = 0; // FF style
	if(elem.style.filter) elem.style.filter.opacity = "alpha(0)"; // IE style
	elem.style.visibility = "visible";
		for(var i=0; i <= 100; i+=10){
           (function(){
           		var el = elem;
                var pos = i;
                // Set the timeout to occur at the specified time in the future
                // note that the time grows -> all animationsteps are called at once here in the loop
                setTimeout(function(){
                // Set the new opacity of the element
                YAHOO.util.Dom.setStyle(el, "opacity", (pos/100));       }, ( pos + 1 ) * 5 ); })();
           }
};

// END Help Popup

// IS24 KALENDER
// links mit der klasse "is24_date" oder "is24-date-past" werden als links für den kalender genutzt
// dsa input feld vom typ text das VOR dem link steht wird mit dem Kalender verbunden
// der link bekommt einen onclick handler welcher dann den kalender anzeigen lässt
// benötigt: yui /.../ calendar.js
function locateCalendar(){
	kalender = {}; // kalender array for storing all calenders on page
	dateDiv = {}; // divs for storing the calender(s)
    var trigger = new Array();
	var element;
    // find calendar icons on page
    trigger[0] = YAHOO.util.Dom.getElementsByClassName("is24-date", "a"); // ordinary calendar
	trigger[1] = YAHOO.util.Dom.getElementsByClassName("is24-date-past", "a"); // calendar with 6 months past time date
    if (trigger[0].length > 0 || trigger[1].length > 0) {
		for (var b = 0; b < 2; b++) {
		for (var a = 0; a < trigger[b].length; a++) {
			var quelle = trigger[b][a];
			while (quelle.previousSibling) {
				if (quelle.previousSibling.type == "text") {
					element = quelle.previousSibling;
					var pos = a;
					// onclick handler for das calendar icon
					trigger[b][pos].pos = a;
					trigger[b][pos].ele = element;
					YAHOO.util.Event.addListener(trigger[b][pos], "click", function(){
						makeCalendar(this, this.ele, this.pos,this.className);
					});
					break;
				}
				quelle = quelle.previousSibling; // got back one sibling
			}
		} // inner for loop
	} // outer for loop
        return false;
    } else {
        return false;
    }
}
// Kalender muss Datumsformat Tag.Monat.Jahr haben!!
function makeCalendar(trigger, element, count, classname){
    // create container, if not already existent
    if(!document.getElementById("calendar"+count)){
	    dateDiv[count] = document.createElement("div");
	    dateDiv[count].setAttribute("style", "position:absolute;top:1;left:1;backgroundColor:white;visibility:visible;z-index:30;"); // set styles for later manipulation
	    dateDiv[count].id = "calendar"+count;
	    document.body.appendChild(dateDiv[count]);
    }
    
    var mycal = YAHOO.util.Dom.get("calendar"+count);
    YAHOO.util.Dom.setX(mycal, YAHOO.util.Dom.getX(trigger)  ); // Frank: Kalender liegt ueber dem Icon
    YAHOO.util.Dom.setY(mycal, YAHOO.util.Dom.getY(trigger)  ); 
    
    YAHOO.util.Dom.addClass(document.body, "yui-skin-sam"); // damit der yui-CSS-style greift...
    
    if(typeof kalender[count] == "undefined"){
	    kalender[count] = new YAHOO.widget.Calendar("kalender","calendar"+count); // yahoo kalender erzeugen, global
	    kalender[count].inputElement = element; // callback to the input element
		kalender[count].cfg.setProperty("close",true); // close icon zum kalender adden
		
		if (classname == "is24-date") {
			kalender[count].cfg.setProperty("mindate", new Date()); // allow only future dates 
		}
		else if(classname == "is24-date-past") {
			// assume past time calendar and substract 6 months
			var now = new Date();
			var nowMonth = now.getMonth(); // present month
			var nowYear = now.getFullYear(); // present year
			if (nowMonth - 6 < 0) {
				var rest = (nowMonth - 6) * -1;
				nowMonth = 11 - rest; // substract 
				nowYear = nowYear - 1;
			}
			else {
				nowMonth = nowMonth - 6;
			}
			
			var before = new Date(nowYear,nowMonth);
			//console.info("minimum datum: "+before.getDate()+"   "+nowMonth+"-"+nowYear);
			kalender[count].cfg.setProperty("mindate", new Date(before)); // allow past time dates
			kalender[count].cfg.setProperty("maxdate", new Date(new Date().getTime()-(1000*60*60*24))); // allow max yesterday to be picked
		}
		
	    // german localisation
	    kalender[count].cfg.setProperty("MONTHS_SHORT",   ["Jan", "Feb", "M\u00E4r", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"]); 
	    kalender[count].cfg.setProperty("MONTHS_LONG",    ["Januar", "Februar", "M\u00E4rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"]);
	    kalender[count].cfg.setProperty("WEEKDAYS_1CHAR", ["S", "M", "D", "M", "D", "F", "S"]);
	    kalender[count].cfg.setProperty("WEEKDAYS_SHORT", ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"]);
	    kalender[count].cfg.setProperty("WEEKDAYS_MEDIUM",["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam"]);
	    kalender[count].cfg.setProperty("WEEKDAYS_LONG",  ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"]);
	    
	    kalender[count].cfg.setProperty("START_WEEKDAY", 1); 			// Week begings with Monday
	    kalender[count].cfg.setProperty("DATE_FIELD_DELIMITER", ".");	// date values are connected with "." i.e. "23.12.2007"
	    kalender[count].cfg.setProperty("MDY_DAY_POSITION", 1);
	    kalender[count].cfg.setProperty("MDY_MONTH_POSITION", 2);
	    kalender[count].cfg.setProperty("MDY_YEAR_POSITION", 3);
	}
	    // take date of input field, if existent
	    if(kalender[count].inputElement.value != "") {
	        var eingabe;
	        if(kalender[count].inputElement.value.indexOf(".") != -1) eingabe = kalender[count].inputElement.value.split(".");
	        if(kalender[count].inputElement.value.indexOf("/") != -1) eingabe = kalender[count].inputElement.value.split("/");
	        if(eingabe[2].length < 4) eingabe[2] = "20"+eingabe[2]; // if two digit year is inputed
	        kalender[count].cfg.setProperty("pagedate", eingabe[1]+"."+eingabe[2] );
	        var datestring = eingabe[0]+"."+eingabe[1]+"."+eingabe[2];
	        kalender[count].cfg.setProperty("selected", datestring);
	    }
	    else {
	    	kalender[count].cfg.setProperty("selected", new Date().toString() );
	    } 
	// show only if corresponding input element is not disabled	
	if (!kalender[count].inputElement.disabled) {
		kalender[count].render();
		kalender[count].show();
	}
    
    // set calendar events
    kalender[count].selectEvent.subscribe(function(type,args){
        var datum = args[0].toString();
        var datumNeu = datum.split(",");
        datum = datumNeu[2]+"."+datumNeu[1]+"."+datumNeu[0];
        kalender[count].inputElement.value = datum;
        kalender[count].hide(); // calendar closes on selection
        } );
}
/* ------------------ Ende KALENDER ------------------------------------------------------------*/

/* ------------------- Podcast Tracking ----------------------------------------------------*/
// Functions sends Tracking Information to Indextools+sitestat, only for podcast tracking!
function sendPodcastTracking(trackingValue){
try{
		var actionnumber = "21";
	var video = (typeof(trackingValue) == "string") ? trackingValue : "";
	
	// Nedstat tracking
	/*if (typeof(sitestat) != "undefined") {
		if (typeof ns_pixelUrl != "undefined") {
			tmpUrl = ns_pixelUrl.substring(0, ns_pixelUrl.indexOf('&')); // get PixelURL
		}
		else {
			return false;
		}*/
		
		// documentgroup1 holen
		var docgroup = dg1; 
		
		// videoname und spieldauer auflösen
		var daten = trackingValue.split("-");
		var videoName = daten[0];
		var spielDauer = daten[1];
		sitestat(TRACKING_PREFIX + "&ns_event=21&ns_type=hidden&dg1=" + docgroup + "&sdauer=" + spielDauer + "&vname=" + videoName);
	
}catch(e){ }
}

/* -------------------ende Podcast Tracking ----------------------------------------------------*/

function trackIndextools(action, params){
/* deprecated */
	trackNedstat(action, params);
}

// indextools tracking function for action tracking
function trackNedstat(action,params){
    if(typeof(action) != "string") return false;
    if(action == "22") action = "28"; // action value was changed 
    
    if(params){
       	var count = params.cf22 || ""; // Zählereignis
        var dg3 = params.cf26 || ""; // docgroup3
        var dg4 = params.cf27 || ""; // docgroup4
        var plz = params.cf49 || ""; // PLZ
        var semtyp = params.cf56 || ""; // Seminartyp
    }
    
    try{
	    /*if (typeof(sitestat) != "undefined") {
			if (typeof ns_pixelUrl != "undefined") {
				tmpUrl = ns_pixelUrl.substring(0, ns_pixelUrl.indexOf('&')); // get PixelURL
			}
			else {
				return false;
			}*/
			
			// documentgroup1 holen
			var docgroup = dg1 || "";
			
			sitestat(TRACKING_PREFIX + "&ns_event=" + action + "&ns_type=hidden&dg1=" + docgroup + "&count=" + count + "&mpl=" + mpl + "&dg1=" + dg1 + "&dg2=" + dg2 + "&dg3=" + dg3 + "&dg4=" + dg4 + "&plz=" + plz + "&semtyp=" + semtyp);
		}
	catch(e){}
}


// ------------------------------------------------------------


//  ------------------------------------------------------------
/**
 * -------------------------------------------------------------
 * IS24 legacy scripts
 * -------------------------------------------------------------
 *
 * Methods from former website, kept alive due to downwards compatibility.
 *
 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 * !IMPORTANT! 
 * NO NEW IS24 RELATED SCRIPTS BELOW THIS SECTION PLEASE!
 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 *
*/

function popup_small() { 
	small(); 
}
function small()	   { }
function popup()	   { }
function popup_large() { }
function yellow()	  { }
function postbank()	{ }
function help()		{ }
function haro()		{ }  
function umfrage0402() { }
function popup_exposeimage() { }

// #################################################################

var helper;
// Fenster oeffnen
function open_window( titel, name, breite, hoehe, look ) {
	if( helper ) {
		helper.close();
	}
	helper = window.open(titel, name, 'width='+breite+',height='+hoehe+','+look);
};

function small()		{ open_window( '', 'tracks', 186, 186, 'resizable=1,scrollbars=0,toolbar=0,status=0,menubar=0,location=0,directories=0' ); }
function popup()		{ open_window( '', 'tracks', 640, 440, 'resizable=1,scrollbars=1,toolbar=1,status=0,menubar=1,location=0,directories=0' ); }
function popup_large()  { open_window( '', 'tracks', 640, 600, 'resizable=1,scrollbars=1,toolbar=1,status=0,menubar=1,location=0,directories=0' ); }
function popup_microsite()  { open_window( '', 'tracks', 640, 500, 'resizable=1,scrollbars=1,toolbar=0,status=0,menubar=0,location=0,directories=0' ); }
function popup_800600() { open_window( '', 'tracks86', 800, 600, 'resizable=1,scrollbars=1,toolbar=0,status=0,menubar=0,location=0,directories=0' ); }
function yellow()	   { open_window( '', 'yellow', 640, 620, 'resizable=1,scrollbars=1,toolbar=1,status=0,menubar=1,location=0,directories=0' ); }
function postbank()	 { open_window( '', 'postbank', 600, 500, 'resizable=1,scrollbars=1,toolbar=0,status=1,menubar=0,location=0,directories=0' ); }
function ytong()		{ open_window( '', 'ytong', 385, 515, 'resizable=1,scrollbars=1,toolbar=0,status=0,menubar=0,location=0,directories=0' ); }
function help()		 { open_window( '', 'help', 200, 320, 'resizable=1,scrollbars=1,toolbar=0,status=0,menubar=0,location=0,directories=0' ); }
function haro()		 { open_window( '', 'tracks', 750, 470, 'resizable=1,scrollbars=0,status=0,menubar=0,location=0,directories=0' ); }
function umfrage0402()  { open_window( '', 'umfrage', 800, 750, 'resizable=1,scrollbars=1,toolbar=0,status=0,menubar=0,location=0,directories=0' ); }
function popup_exposeimage(){ open_window( '', 'expimage', 820, 750, 'resizable=1,scrollbars=1,toolbar=1,status=0,menubar=1,location=0,directories=0' ); }

// #################################################################

function clearField( Formname, Fieldname, Fieldvalue) {
	if ( document.forms[Formname].elements[Fieldname].value == Fieldvalue ) document.forms[Formname].elements[Fieldname].value = '';
};

// #################################################################

function FMsetCookie(name, val) {
	
	//var today = new Date();
	//var expire = 3600000*24*30; // 30 Tage
	//var the_date = new Date(today.getTime() + expire);
	//var the_cookie = name + "=" + val + "; nfti_date="+escape(today) + "; expires=" + the_date.toGMTString();
	//document.cookie = the_cookie;
	
	
	var host = determineCookieHost();

	if (host == null) {
		//do not set cookie domain
		setCookie(name, val, false, false, false, false, false, true);
	} else {
		//do set cookie domain 
		setCookie(name, val, false, false, host, false, false, true);
	}
//	document.cookie = name + "=" + val;
};

/*
  This methode is Strongly DEPRECATED.
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  The path must be the same as the one which was used to create the cookie.
  Otherwise you are not be able to remove the cookie.
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
function FMremoveCookie(name){
	var host = determineCookieHost();///
	if(host==null) deleteCookie(name,"/",false);
	else deleteCookie(name,"/",host);
};

/*
  This methode is DEPRECATED.
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  Path must be specified. 
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

*/
function setPersistentCookie(name, val, duration) {
	
	var today = new Date();
	var expire = 3600000*24*duration; // duration in Tagen
	var the_date = new Date(today.getTime() + expire);
	
	var host = determineCookieHost();
	//setCookie(name, value, expires, path, domain, secure, ntfi_date)
	if (host == null) {
		//do not set cookie domain
		setCookie(name, val, the_date, '/', false, false, today, true);
	} else {
		//do set cookie domain 
		setCookie(name, val, the_date, '/', host, false, today, true);
	}
	
	//var the_cookie = name + "=" + val + "; nfti_date="+escape(today) + "; expires=" + the_date.toGMTString()+ "; path=" + "/";
	//document.cookie = the_cookie;
	//document.cookie = name + "=" + val;
};

/*
This methode ist strongly deprecated.
It returns the value of only one possible cookie with the given name.
But there can exist several cookies with the same name.
*/
function FMgetCookie(name) {
	var the_cookie = document.cookie;
	the_cookie = unescape(the_cookie);
	the_cookie_split = the_cookie.split(";");
	//alert (the_cookie_split.length);
	for (i=0;i<the_cookie_split.length;i++) {
		var part_of_split = the_cookie_split[i];
		var find_name = part_of_split.indexOf(name);
		if (find_name!=-1) {
			var equal = part_of_split.indexOf("=") + 1;
			var value_of_split = part_of_split.substring(equal,part_of_split.length);
			return value_of_split; // when the cookie's content is empty you maybe will get also 0.
		}
	}
	return 0;
};

function isPopupClosed() {
	if (  window.MyScout != null && window.MyScout.closed == true ) { 
		FMsetCookie('myscoutCookie', 1);
	}
};

// #################################################################


function openHelpPopup(htmlfile){
	var WBreite = 323;
	var WHoehe	= 242;
	var scrolling='no'
	if (screen.availHeight-40 <= WHoehe)
		{
		WHoehe = screen.availHeight-40;
		scrolling = 'yes';
		}
	if (screen.availWidth-40 <= WBreite)
		{
		WBreite = screen.availWidth-40;
		scrolling = 'yes';
	}
	var options = "scrollbars="+scrolling+",toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,top=183,left=114,width="+WBreite+",height="+WHoehe;	
	var fenster = window.open(htmlfile,'infopopup', options);
	fenster.focus();
}

function openHelpPopupBig(htmlfile,vsize,hsize){
	var WBreite = hsize;
	var WHoehe  = vsize
	if(WBreite == 0)
		WBreite = 323;
	if(WHoehe == 0)
		WHoehe	= 242;
	var scrolling='no'
	
	if (screen.availHeight-40 <= WHoehe)
		{
		WHoehe = screen.availHeight-40;
		scrolling = 'yes';
		}
	if (screen.availWidth-40 <= WBreite)
		{
		WBreite = screen.availWidth-40;
		scrolling = 'yes';
	}
	var options = "scrollbars="+scrolling+",toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,top=183,left=114,width="+WBreite+",height="+WHoehe;	
	var fenster = window.open(htmlfile,'infopopup', options);
	fenster.focus();
}

function findInfoPopupText(helptext) {
	for(i=0;i<document.forms.length;i++) {
		for(x=0;x<document.forms[i].elements.length;x++) {
			if(document.forms[i].elements[x].name=='infopopuptext') {
				document.forms[i].elements[x].value=helptext;			
			}			
		}
	}
}


/*
========================================================================


    C O O K I E    A P I


========================================================================
*/

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/
function setCookie(name, value, expires, path, domain, secure, nfti_date, disableEscaping) {
  if (typeof disableEscaping == 'undefined' || disableEscaping == null || disableEscaping != true) disableEscaping = false; 
  var curCookie = name + "=" + 
      ((disableEscaping) ? value : escape(value)) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((nfti_date) ? "; nfti_date=" + ((disableEscaping) ? nfti_date : escape(nfti_date)) : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// returns cookie with specific name
function is24_getCookie(name)
{
	var dc = document.cookie;
	var pos = dc.indexOf(name + "=");
	if (pos != -1)
	{
		var start = pos + name.length + 1;
		var end = dc.indexOf(";", start);
		if (end == -1)
		{
			end = dc.length;
		}
		return dc.substring(start, end);
	}
	return "";
}

// returns specific value from named cookie
// separator separates parameters inside the cookie
// separator2 separates name and values inside the parameters
function is24_getCookieParam(cookiename,name,separator,separator2)
{
	var ck = getCookie(cookiename);
	var ck_neu = '';
	
	if (ck.length > 0)
	{
		var pos = ck.indexOf(name + separator);
		if (pos != -1)
		{
			var start = pos + name.length + 1;
			var end = ck.indexOf(separator2, start);
			if (end == -1)
			{
				end = ck.length;
			}
			return ck.substring(start, end);
		}
	}
	return "";
}

// separator separates parameters inside the cookie
// separator2 separates name and values inside the parameters
function is24_setCookieParam(cookiename, name, value, separator, separator2)
{
	var ck = is24_getCookie(cookiename);
	console.info("cookie geholt "+ck);
	if (ck.length > 0)
	{
		var pos = ck.indexOf(name + separator);
		if (pos != -1)
		{
			var start = pos + name.length + 1;
			var end = ck.indexOf(separator, start);
			if (end == -1)
			{
				end = ck.length;
			}
			ck = ck.substring(0,start)+value+ck.substring(end);
			console.info("neues cookie  "+ck);
		}
		else {
			ck += separator2+name+separator+value;
			console.info("neues cookie  "+ck);
		}
	}
	else {
		ck = name+separator+value;
		console.info("neues cookie  "+ck);
	}
	setPersistentCookie(cookiename, ck, 1095); // set 3 years cookie
	console.info("cookie geschrieben "+is24_getCookie(cookiename));
}

/*
  Cookie's name shouldn't contain '='
  Also Cookie's value shouldn't contain characters like ',' and '= ' and ';'
*/
function getAllCookies() {
    var everycookievalue = document.cookie;
    var mySplit = everycookievalue.split(";");
    var cookieString;
    var resultName;
    var resultValue;
    var pos;
    var cookies = new Array();
    for ( count=0; ( mySplit[count] != undefined ); count++ ) {
        cookieString = mySplit[count] + '';
        cookieString = cookieString.replace(/^\s+|\s+$/g, '');
        pos = cookieString.indexOf('=');
        if (pos == -1) {//for IE
            resultName = cookieString;
            resultValue = '';
        } else {
            resultName = cookieString.substring(0, pos);
            resultValue = cookieString.substring(pos + 1, cookieString.length);
        }
        cookies[count] = [resultName, resultValue];
    }
    return cookies;
}
/*
   It returns an array of values.
*/
function getCookiesWithName(name, comparator) {
    var allCookies = getAllCookies();
    var toReturn = new Array();
    var count = 0;
    for (var i = 0; i < allCookies.length; i++) {
        var cookie = allCookies[i];
        var cookieName = cookie[0] + '';
        var cookieValue = cookie[1] + '';
        if (typeof comparator != 'undefined') {
            if (comparator(cookieName, name, cookieValue) == true) {
                toReturn[count++] = allCookies[i];
            }
        } else if (cookieName == name) {//Use instead ===  or JSObject.equals
            toReturn[count++] = allCookies[i];
        }
    }
    return toReturn;
}


/*
  It determines instructions for removing cookies.
*/
function getRemovalPrescription() {
    var toReturn = new Array();
    
    var host = determineCookieHost();
    if (host == null) return toReturn;
    
    var serverName = document.location.host;
    var hosts = new Array(false, host, serverName);
    
    var pathName = getDocumentPath();//pathName = parseURL(document.location.href).pathname;
    var paths;
    if (pathName == '/') {
        paths = new Array(false, '/');
    } else {
        paths = new Array(false, '/', pathName);
    }
    
    var count = 0;
    for (i = 0; i < hosts.length; i++) {
        for (j = 0; j < paths.length; j++) {
            toReturn[count++] = [paths[j], hosts[i]];
        }
    }
    return toReturn;
}

function deleteCookiesWithName(name, prescription) {
    var cookies = getCookiesWithName(name);
    var before = cookies.length;
    if (before == 0) return before;
    
    if (typeof prescription != 'object') {
        prescription = getRemovalPrescription();
    }
    if (prescription.length == 0) {
        return before;
    }
    var instruction = prescription[prescription.length - 1];
    prescription.length = prescription.length - 1;//pop
// use logger instead    
//                                    document.write('<b>Vorher:</b> ---->' + document.cookie);
//                                    document.write("<br><br>");
//                                    document.write('<b>RemovalPrescription</b> ---->' + instruction);
//                                    document.write("<br><br>");
    deleteCookie(name, instruction[0], instruction[1]);
//                                    document.write('<b>Nachher:</b> ---->' + document.cookie);
//                                    document.write("<br><br>");
    var after = getCookiesWithName(name).length;
    if (after == 0) return after;//Volltreffer
    if (after == before) {//Cookie couldn't be deleted. Either no new cookie was created. Wrong removal instruction.
        after = deleteCookiesWithName(name, prescription);//go further and try the next removal instruction
    } else if (after > before) { //disaster fund 
        deleteCookie(name, instruction[0], instruction[1]);//remove the unintended created cookie instantly 
        after = getCookiesWithName(name).length;
        if (after > before) {
            return after;//should never happen. hopefully the very rare case. consider to throw an exception.
        }
        after = deleteCookiesWithName(name, prescription);//go further with the next removal instruction
    } else if (after < before) { //cookie removed successfully
        //Weitere evtl. vorhandene Cookies (mit gleichen Namen) Löschen.
        after = deleteCookiesWithName(name, prescription);//go further with the next removal instruction
    }
    return after;
}

function deleteCookie(name, path, domain) {
    var expires = new Date(1980, 0, 1);
    setCookie(name, '', expires, path, domain, false, false, false);
}

function printCookies(cookies) {
    if (typeof cookies != 'object' || cookies == null) {
        cookies = getAllCookies();
    }
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var cookieName = cookie[0] + '';
        var cookieValue = cookie[1] + '';
        document.write(cookieName + '---->' + cookieValue);
        document.write("<br><br>");
    }
}

/**
 * -------------------------------------------------------------
 * determine the value of the cookie host ignoring all sub domains.
 * -------------------------------------------------------------
 *
 *
*/
function determineCookieHost() {
    var server = window.location.hostname;
    
    var host = null;
    var sub = server.split('.');
    switch (sub.length) {
        case 0: {
            break;
        }
        case 1: {
            break;
        }
        case 2: {
            //same behavior as returning null
            //host = server;
            break;
        }
        /*
        //same behavior as default
        case 3: {
            host = sub[1] + "." + sub[2];
            break;
        }
        */
        case 4: {            
            if (isNumber(sub[3])) {//Is server an IP address?
                break;//If it is true, then return null.
            } else {
              //do the same as specified in default case
            }
        }
        default: {
            host = '.' + sub[sub.length - 2] + '.' + sub[sub.length - 1];
            //host = server.substring(server.indexOf('.') + 1);
            break;
        }
    }
    return host;
};

function CookieClass(name, value, expires, path, domain, secure, nfti_date, disableEscape) {
    this.name = name;
    this.value = value;
    this.domain = domain;
    this.path = path;
    this.secure = secure;
    this.expires = expires;
    this.nfti_date = nfti_date;
    this.disableEscape = disableEscape;
}

/**
 * -------------------------------------------------------------
 * Wheter the giving string is a number or not
 * -------------------------------------------------------------
 *
 *
*/
function isNumber(sText) {
	if (sText=="") return false;
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	var dotCnt = 0;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (Char==".") dotCnt = dotCnt +1;
		if (ValidChars.indexOf(Char) == -1 || dotCnt>1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}

//parse a URL to form an object of properties 
function parseURL(url) {
    //save the unmodified url to href property
    //so that the object we get back contains
    //all the same properties as the built-in location object
    var loc = { 'href' : url };

    //split the URL by single-slashes to get the component parts
    var parts = url.replace('//', '/').split('/');

    //store the protocol and host
    loc.protocol = parts[0];
    loc.host = parts[1];

    //extract any port number from the host
    //from which we derive the port and hostname
    parts[1] = parts[1].split(':');
    loc.hostname = parts[1][0];
    loc.port = parts[1].length > 1 ? parts[1][1] : '';

    //splice and join the remainder to get the pathname
    parts.splice(0, 2);
    loc.pathname = '/' + parts.join('/');

    //extract any hash and remove from the pathname
    loc.pathname = loc.pathname.split('#');
    loc.hash = loc.pathname.length > 1 ? '#' + loc.pathname[1] : '';
    loc.pathname = loc.pathname[0];

    //extract any search query and remove from the pathname
    loc.pathname = loc.pathname.split('?');
    loc.search = loc.pathname.length > 1 ? '?' + loc.pathname[1] : ''; 
    loc.pathname = loc.pathname[0]; 

    //return the final object 
    return loc; 
}

function getDocumentPath() {
    var path = '/';
    var href = document.location.href;
    if (href.indexOf('http:') == -1) return path;
    var s = href.split("/");
    for (var i = 3; i < ( s.length - 1 ); i++) {
        path += s[i] + '/';
    }
    return path;
}

function unescapeRepetitive(escapedString, character) {
    var escapedSign = escape(character);
    if (escapedSign.indexOf('%') == -1) return escapedString;
    var matcher = '(%)(25)*('+ escapedSign.substr(1,2) +')';
    var reg = new RegExp(matcher, 'g');
    return escapedString.replace(reg, character);
}

function repaireCookies_AcceptCookies() {
    var cookies = getCookiesWithName('ImmobilienScout24_cookieAccept');
    if (cookies.length == 0) return;
    var exitcode = deleteCookiesWithName('ImmobilienScout24_cookieAccept');
    if (exitcode != 0) {
        //alert('Es ist leider ein Fehler aufgetretten. Die im Browser hinterlegten Cookies weisen Inkonsisten auf. Um weitere Fehler zu vermeiden, sollten Sie Cookies der Immobilienscout24 löschen. Wir bitten dies zu entschuldigen.');
        return;
    }
}

function repaireCookies_PersistentState() {
    var comparator = function(p1,p2, p3) {
        if (p1 == p2) {
            if (p3.indexOf('%') != -1 || p3.indexOf(':') == -1 || p3 == '' || p3 == '\"' ) return true;
        }
    }
    //iterate over all cookies with the persistentState and search for an unescaped one.
    //is it an unescaped one? Then delete all cookies with the same name w/o exceptions.
    var cookies = getCookiesWithName('persistentState', comparator);
    if (cookies.length == 0) return;
    
    var exitcode = deleteCookiesWithName('persistentState');
    if (exitcode != 0) {
        //alert('Es ist leider ein Fehler aufgetretten. Die im Browser hinterlegten Cookies weisen Inkonsisten auf. Um weitere Fehler zu vermeiden, sollten Sie Cookies der Immobilienscout24 löschen. Wir bitten dies zu entschuldigen.');
        return;
    }
}

function repaireCookies_FPC() {
    var comparator = function(p1,p2, p3) {
        return p1.indexOf(p2) == -1 ? false : true;
    }
    
    var cookies = getCookiesWithName('fpc', comparator);
    if (cookies.length == 0) return;
    
    var cookieName;
    var cookieValue;
    for (var i = 0; i < cookies.length; i++) {//iterate over all fpc cookies and search for an unescaped one.
        var cookie = cookies[i];
        cookieName = cookie[0] + '';
        cookieValue = cookie[1] + '';
        if (cookieValue != '' && cookieValue.indexOf('%') == -1) {//is it an unescaped one?
            break;//take it
        } else {
            if (i == cookies.length -1 && cookieValue != '') {//last chance. there ist no valid fpc. take the invalid fpc und use it.
                cookieValue = unescapeRepetitive(cookieValue, '|');
                cookieValue = unescapeRepetitive(cookieValue, '=');
            }
        }
    }
    
    //retrieve all fpc cookie names
    var fpcCookieNames = new Object();
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var cn = cookie[0] + '';
        var cv = cookie[1] + '';
        fpcCookieNames[cn] = cv;
    }
    
    for (cn in fpcCookieNames) {
        var exitcode = deleteCookiesWithName(cn);
        if (exitcode != 0) {
            //alert('Es ist leider ein Fehler aufgetretten. Die im Browser hinterlegten Cookies weisen Inkonsisten auf. Um weitere Fehler zu vermeiden, sollten Sie Cookies der Immobilienscout24 löschen. Wir bitten dies zu entschuldigen.');
            return;
        }
    }
        
    var expires = new Date();
    expires.setTime(expires.getTime() + 1000 * 60 * 60 * 24 * 365);
    
    var host = determineCookieHost();
    if (typeof host == 'undefined' || host == null) host = false;
    
    setCookie(cookieName, cookieValue, expires, '/', host, false, false, true);
}

function repaireCookies_S_SYSU() {
	//TODO: Frank Berlin
/*	var cookies = getCookiesWithName('_S_SYSUCOOKIE');
	console.info(cookies.length);
    if (cookies.length == 0) return;
    var exitcode = deleteCookiesWithName('_S_SYSUCOOKIE');
    if (exitcode != 0) {
        //alert('Es ist leider ein Fehler aufgetretten. Die im Browser hinterlegten Cookies weisen Inkonsisten auf. Um weitere Fehler zu vermeiden, sollten Sie Cookies der Immobilienscout24 löschen. Wir bitten dies zu entschuldigen.');
        return;
    }
   */
}

function repaireMalformedCookies() {
    //repair
    repaireCookies_AcceptCookies();
    repaireCookies_PersistentState();
    repaireCookies_S_SYSU();
    //repaireCookies_FPC();

    //ignore
    //BIGIP
    //SSO
    //IS24_last_search
    //selectedpois

    //session cookies
    //IS24VisitId;
    //IS24VisitIdSC;

    //not changed yet
    //expose_cd
    
    //should have 
    //is24uv/IS24
    
    //?
    //POPUPCHECK
    //itfpctmp
    //otp_typ  
}








