var yPos, xPos;
var SUBMIT_CLICK = true;
var origDroppiTop = 240;
var origDroppiWidth = 30;
var dragging = false; // wird gerade gedraggt
var locationHitList = "" ;//ods
var locationHitIndex = "" ;//ods
var openSuggest = "";
var documentLoaded = false;
var os ="";
var isMac = "";
var BFSide = "";

/**
 * PRE-Document-Ready, we need once the curretn x and y pos of
 * cursor because clicking too quick on pos-relevant actions crashes
 * when xPos anf yPos is NaN
 */
$(document).one('mouseover', function(event) {
    xPos = event.pageX;
    yPos =event.pageY;
});

function init_noscript(){

	//wegen noscript hier die Hintergrundbilder manuell setzen
	if(ge('what_search')!==null && ge('where_search')!==null){
		$('#where_search_overlay,#what_search_overlay').css("background-position","0 0");
	}
	if(ge('what_search_s')!==null){
		$('#what_search_s_overlay').css("background-position","0 0");
	}
	if(ge('where_search_m')!==null){
		$('#where_search_m_overlay').css("background-position","0 0");
	}
	if(ge('regioframe')!==null){
		$('#regioframe').css('display','inline');
	}
	if(ge('tagcloud')!==null){
		$('#tagcloud').css('display','inline');
	}
	$('#radial_search_inner').show();
	if($('#start_page').size()<1 && $('#map_search').size()<1 && $('#product_search').size()<1 && $('#advert_page').size()<1){
		//$('#commercial_ads').css('background-image','url("../../static/css/img/bg/bg_commercials.png")');
		//$('#commercial_ads span.comm_text').css('background-image','url("../../static/css/img/bg/bg_commercials_top.png")');
		//$('#commercial_bottom').show();
	}

	if($('.video_page').size()<1) /* Video-Community*/
	{
		/* inaktive Filter */
		filter_inactive = '#search_delimiter div.sel_inactive';
		if($(filter_inactive).size()>0)
		{
			$(filter_inactive).css('background-image','url("../../static/css/img/bg/bg_search_selection_inactive.png")');
		}
		/* aktive Filter */
		filter_active = '#search_delimiter div.sel_active';
		if($(filter_active).size()>0)
		{
			$(filter_active).css('background-image','url("../../static/css/img/bg/bg_search_selection.png")');
		}
	}
	else
	{
		if($.browser.msie && $.browser.version === "6.0"){
			$('#search_delimiter div.selection').css('background-image','url("../../static/css/img/bg/bg_search_video_selection_ie.png")');
		}
		else{
			$('#search_delimiter div.selection').css('background-image','url("../../static/css/img/bg/bg_search_video_selection.png")');
		}
	}

	//Merk Icons wieder einblenden
	if($('div.search_hit_links').length>0){
		$('div.search_hit_links div.iconshided').show();
	}

	if($.browser.msie && $.browser.version=="6.0")
	   $('.select_selection').show();

	// End noscript notwendiges
}

function init_persbookmarking(){
	if($('#pers_bookmarking').length>0){
		   if($.browser.msie && $.browser.version == "6.0"){
		   		 $('#droppi').css('height',$('#content').height()+'px');
		       $(window).scroll(function(){
		          fixPos();
			    });
		   }

		   $('.draggable').Draggable({revert:true,zIndex:77,
		        ghosting:true,
		        onStart: function(){
	                        $('#dragHelper div:first').css("background-color", "transparent");
	                        //relativ ungetestet, aber es musste schnell gehen
	                        xposi = xPos-50;
	                        $('#droppi').css("width",xposi+"px");
	                        $('#droppi').css("top","0px");
	                        $('#dragHelper .hit_result_tel img, #dragHelper .advert_gratis_call').hide();
	                        dragging = true;
	                        //bug 2635
	                        //this.style.position = "static";

		        },
		        onStop: function(){
		          window.setTimeout(function(){dragging = false;},500);

		        },
		        onDrag:function(){;
		        	//console.debug($('#dragHelper').html());
		        }
		   });
		   $('#search_hit_page #droppi').Droppable({
		        accept : 'draggable',    tolerance:'pointer',
		        onDrop: function (drag){
		                    dropBookmark(drag);
		                    $('#droppi').css({"width":"30px","top":"240px"});
		                    window.setTimeout(function(){dragging = false;},1000);
		                    if($.browser.msie && $.browser.version == "6.0")
		                        ;//drag.style.position = "static";

		                }
		   });
		   $('#advert_page #droppi').Droppable({
	            accept : 'draggable',    tolerance:'pointer',
	            onDrop: function (drag){
	                        iDropBookmark(drag);
	                        $('#droppi').css({"width":"30px","top":"240px"});
	                        dragging = false;
	                    }
	       });
	    }

}

var	adWidthContainer = 0;
var	adWidthIFrame = 0
var adWidthCommercial = 0;

function handleAds(){
	// if($('#start_page').size()<1 && $('#map_search').size()<1 && $('#product_search').size()<1 && $('#advert_page').size()<1){
	if($('.morecommercial').size()) {
		window.setTimeout(function(){
			 if($('#adIframe').size()<1)
				 return;
			 resizeAds();
			 window.setTimeout(function(){
				 resizeAds();
			 },3000);
			 showAds();
		  },30);

	}
}
function showAds(){
	$('#commercial_ads').css('border','1px solid white');
	adWidthCommercial = $('#commercial_ads').width();
	 wrapperWidth = $('#wrapper').width();
	 newContainerWidth = wrapperWidth+adWidthCommercial+10;
     wrapperMargin = adWidthCommercial+10;
     if($('body').width()<newContainerWidth-20)
     $('body').css('width',newContainerWidth+'px');
	 $('#wrapper').css('margin-right',wrapperMargin+'px');
	 $('#adIframe').css("visibility","visible");
}

function resizeAds(){
	try {
		if($.browser.msie){
			 adWidthContainer = ge('adIframe').Document.body.scrollWidth+7;
			 adWidthIFrame = ge('adIframe').Document.body.scrollWidth;
			 $('#adIframe').css("height",ge('adIframe').Document.body.scrollHeight+"px");
			 $('#adIframe').css("width",adWidthIFrame+"px");
			 $('#commercial_ads').css("width",adWidthContainer+"px");
		 } else {
	   	     adWidthContainer = ge('adIframe').contentDocument.body.scrollWidth+7;
	   	     adWidthIFrame = ge('adIframe').contentDocument.body.scrollWidth;
			 $('#adIframe').css("height",ge('adIframe').contentDocument.body.scrollHeight+"px");
			 if($('#adIframe').width()==192){
				 adWidthIFrame = adWidthIFrame-12;
			 } else {
				 ;
			 }
			 $('#adIframe').css("width",adWidthIFrame+"px");
			 $('#commercial_ads').css("width",adWidthContainer+"px");
	    }
	} catch( e ) {

	}
}

function configureFlash(){
    if($('#commercial_01 object,#commercial_01 iframe').size()<1  )
    	return;
    //ueberlagerndes Flash FF:
    $('embed').attr("wmode","transparent");
    //hart aber notwendig: das <noscript> raus, sonst gehen manche Banner nicht
    $('#commercial_01 noscript').remove();
    // IE
    var objectos = $('#commercial_01 object');
    var str = "";
    str =   objectos.html();
    if(str===null)
    	return;
    str+= "<param name='wmode' value='transparent'></object>";
    var new_object = "<object id='"+objectos.attr('id')+"' codebase='"+objectos.attr('codebase')+"' width='"+objectos.attr('width')+"' height='"+objectos.attr('height')+"' wmode='transparent' classid='"+objectos.attr('classid')+"'>";

    $('#commercial_01 object').remove();
    $('#commercial_01').append(new_object+""+str);
}

function activateRadialSearch(){
    $('#radial_search img.overlay').hide();
    if($.browser.msie){
        $('#radial_search_inner').css('visibility','visible');
         initSlider();
    }
    else{
         $('#radial_search_inner').css('visibility','visible');
        window.setTimeout(function(){ initSlider(); },500);
    }

}

function enableFilters(){

    if(!$.browser.msie){
        $('#search_delimiter img.overlay').hide();
         $('#search_delimiter .selection_inner').fadeIn(500);
     }
     else{
        if($.browser.version != "6.0" || $('.video_page').size()>0){
            $('#search_delimiter img.overlay').hide();
            $('#search_delimiter div.selection_inner').show();
        }
     }

}

//Alle Elemente, die eine Mouse Position ben�tigen, werden hier initialisiert
function initPosRelevantsItems(){
    $("a,div.draggable").mouseover(function(e){
        xPos =e.pageX;
        yPos =e.pageY;
   });
}


function getViewportDimensions() {
   var intH = 0, intW = 0;

   if(self.innerHeight) {
      intH = window.innerHeight;
      intW = window.innerWidth;
   }
   else {
       if(document.documentElement && document.documentElement.clientHeight) {
           intH = document.documentElement.clientHeight;
           intW = document.documentElement.clientWidth;
       }
       else {
           if(document.body) {
               intH = document.body.clientHeight;
               intW = document.body.clientWidth;
           }
       }
   }
   return {
       height: parseInt(intH, 10),
       width: parseInt(intW, 10)
   };
}

// aendern der Inhalt-Dimensionen bei ver&aumlndern der Browser-Breite
function initMap()
{

	if($('#popup').length>0)
    {
    	$('#map').height(getViewportDimensions().height-220);
	}
	else
	{
		$('#map').height(getViewportDimensions().height-300);
	}


    	if ((getViewportDimensions().width) >=1024){
    		$('#map_search #commercial_ads').css('left', (getViewportDimensions().width-210));
    		if($('#popup').length>0)
    		{
    		$('#map_search #content').width(getViewportDimensions().width-44);
    		}
    		else
    		{
    		$('#map_search #content').width(getViewportDimensions().width-250);
    		}
    	}
    	else
    	{
    		$('#map_search #commercial_ads').css('left', 800);
    		$('#map_search #content').width(755);



    	}
    	$(window).resize(function(){
		 	if($('#popup').length>0)
		    {
		    	$('#map').height(getViewportDimensions().height-220);
			}
			else
			{
				$('#map').height(getViewportDimensions().height-300);
			}

		 if ((getViewportDimensions().width) >=1024){

	    	$('#map_search #commercial_ads').css('left', (getViewportDimensions().width-210));
	    	if($('#popup').length>0)
    		{
    		$('#map_search #content').width(getViewportDimensions().width-44);
    		}
    		else
    		{
    		$('#map_search #content').width(getViewportDimensions().width-250);
    		}
    	}
    	else
    	{

    		if($('#popup').length>0 && (getViewportDimensions().width) >=800)
    		{
    		$('#map_search #content').width(getViewportDimensions().width-44);
    		}
    		else
    		{
    		$('#map_search #commercial_ads').css('left', 800);
    		$('#map_search #content').width(755);
    		}

    	}
		});
}

// aendert die Position des Merkzettels, sobald es ein Wallpaper-Banner gibt
// Zudem wird die Startseite vergrert auf Screenhoehe
function initWallpaper(){
	$('#wrapper').css('min-height',getViewportDimensions().height);
	if($.browser.msie && $.browser.version == "6.0"){
        $('#wrapper').css('height',getViewportDimensions().height);
        $('#advert_page #pers_bookmarking, #product_search #pers_bookmarking, #privat_search #pers_bookmarking').css('top', '312px');
    }
    else{
     $('#pers_bookmarking').css('top', '358px');
     $('#advert_page #pers_bookmarking, #product_search #pers_bookmarking, #privat_search #pers_bookmarking').css('top', '312px');
    }
}

// Aendern der Farbwerte eines Inputs beim Reinclicken
function init_inputOnclickColorValues(){
	$('input.se_styled_input').focus(function(){
		this.value="";
		this.style.color="#000";
		this.style.fontSize="14px";
		this.style.fontWeight="bold";
		this.style.topPadding="7px";
	});
	$('select.se_styled_input').focus(function(){
		this.style.color="#000";
	});
	$('input:password').focus(function(){
		this.value="";
		this.style.color="#000";
	});
}

// Preloader fuer die Hovers der Tab-Nav
function initPreloader(){
	$('#main_nav li').preload({
    find: '.png',
    replace: '_ovr.png'
	});
	$('#what_search_inner').preload({
    find: '_what.png',
    replace: '.png'
    });
    $('#where_search_inner').preload({
    find: '_where.png',
    replace: '.png'
    });
}
var scrolledPos = 0;
//Initialisierung der drei filter auf der Trefferliste
function initScroller(which,heightlimit){
    //Hoehe bestimmen
    var height = $('#delimiter_list_'+which).height();
    $('#scroll_container_'+which).css("overflow-y","hidden");
    if(height>heightlimit){
        height = heightlimit;
       $('#scroll_container_'+which).css("overflow-y","auto");

    }
    $('#scroll_container_'+which).height(height);
    return;
}

function initBrowserChanges(){
   //Der Slider muss ein GIF sein, weil der IE6 keine PNG Halbschatten verarbeitet
    if($.browser.msie && $.browser.version == "6.0"){
        $('#radial_anfasser').attr('src=','./../static/img/icons/icon_anfasser.gif');

	$('.video_page img.btn_play,.video_print_page img.btn_play').each(function()
    	{
    		var src = this.src;
			var new_src= src.replace(/.png/, "_ie.gif");
			this.src= new_src;

    	}
    	)


    }
    if($.browser.msie){
        initMainNavHover();
    }
    try {
         document.execCommand("BackgroundImageCache", false, true);
      } catch(err) {}

      if(jQuery.browser.msie && jQuery.browser.version <= 6){
         try {
             document.execCommand('BackgroundImageCache', false, true);
          } catch(err) {}
       }


}

function calcRadialDistance(cordx){
    var cordx = Math.round(cordx);
    if(cordx<74){
       if(Math.round((cordx)/7)<1)
        return 1;
       else
        return Math.round((cordx)/7);
    }
    else if(cordx>=74 && cordx < 80)
        return 10;
    else if(cordx>=80 && cordx < 86)
        return 20;
    else if(cordx>=86 && cordx < 92)
        return 30;
    else if(cordx>=92 && cordx < 99)
        return 40;
    else if(cordx>=99 )
        return 50;
}

function calcRadialDistancePixel(dist){
    if (dist<10000)
    return dist/80;
    if (dist==10000)
        return 130;
    if (dist==20000)
     return 150;
   if (dist==30000)
    return 160;
   if (dist==40000)
    return 170;
   if (dist==50000)
    return 180;
   return 35;
}

/*Begin Suggest*/

var arrowCounter = -1;
var suggestInProgress = false;

function lockCursor(which){
    if($.browser.msie){
          var range = ge(which).createTextRange();
          range.collapse(true);
          range.moveEnd('character', $('#'+which).val().length);
          range.moveStart('character', $('#'+which).val().length);
          range.select();
    }
    else{
        ge(which).setSelectionRange($('#'+which).val().length,$('#'+which).val().length);
    }

}

function enableSuggest(){
    SUGGEST_ENABLED = true;
    $('#what_search').removeAttr("autocomplete");
    $('#where_search').removeAttr("autocomplete");
}

function disableSuggest(){
    SUGGEST_ENABLED = false;
    $('#what_search').attr("autocomplete","on");
    $('#where_search').attr("autocomplete","on");
}
function initSuggest(){
    if($('body').attr('id').indexOf('map_') ==-1){
    	$('#search_go').keydown(function(event){
		 if(event.keyCode==13){
              executeSubmit();
              closeAllLayers();
              return true;
          }
    	});

		$('#what_search').keydown(function(event){
		 if(event.keyCode==13 && $('#'+openSuggest+' div.suggest_inner li.hover').size()<1){ //wird der suggestlayer nicht verwendet, bei return(13)submit ausfuehren.
              executeSubmit();
              closeAllLayers();
              return true;
          }
		  if(SUGGEST_ENABLED || ge('show_suggest').checked){
			   $('#suggest_what').bgiframe();
			   if(event.keyCode != 13 && event.keyCode != 38 &&  event.keyCode!=40){
			      if(!suggestInProgress){
			          suggestInProgress = true;
			          window.setTimeout(function(){ // Begin zeitverzoegertes Ajaxen
						   $.getJSON(PATH_TO_SUGGEST_WAS, { search: 'what' , tag: $('#what_search').val() },function (data){
						       openSuggest= "suggest_what";
					            fillWithContent(data);
					            arrowCounter = -1
					            if(data.length!=0){
					               closeAllLayers("suggest_what");
						           openSuggest= "suggest_what";
						           if(openSuggest==="" || openSuggest!="suggest_where"){
						               window.setTimeout(function(){ge('suggest_what').style.display = "block";},50);
						               $('#what_search_inner div.headersearch_error_line').hide();

						               openSuggest = "suggest_what";
						           }
						        }
						        else{
						         closeAllLayers();
						        }
							  } );
							  suggestInProgress = false;
						 },SUGGEST_DELAY
						);    // Ende zeitverzoegertes Ajaxen
					}
			   }
			   else if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode==40) {
			        lockCursor('what_search');
	                handleArrow(event.keyCode);
	           }
		   }
		});
		$('#where_search').keydown(function(event){
		  if(event.keyCode==13 && $('#'+openSuggest+' div.suggest_inner li.hover').size()<1){ //wird der suggestlayer nicht verwendet, bei return(13)submit ausfuehren.
		      executeSubmit();
		      closeAllLayers();
		      return true;
		  }
		   if(SUGGEST_ENABLED || ge('show_suggest').checked){
			   $('#suggest_where').bgiframe();
				if(event.keyCode != 13 && event.keyCode != 38 && event.keyCode!=40){
				  if(!suggestInProgress){
		               suggestInProgress = true;
		               window.setTimeout(function(){ // Begin zeitverzoegertes Ajaxen
						   $.getJSON(PATH_TO_SUGGEST_WO, { search: 'where',tag: $('#where_search').val() },function (data){
					           openSuggest= "suggest_where";
					           fillWithContent(data);
					           arrowCounter = -1
					           if(data.length!=0){
						           closeAllLayers("suggest_where");
							       openSuggest = "suggest_where";
							       if(openSuggest==="" || openSuggest!="suggest_what"){
							           window.setTimeout(function(){ge('suggest_where').style.display = "block";},50);
							           $('#where_search_inner div.headersearch_error_line').hide();
							           if(event.keyCode == 13 || event.keyCode == 38 ||  event.keyCode==40)
							                handleArrow(event.keyCode);
							           openSuggest = "suggest_where";
							       }
							   }
							   else{
							     closeAllLayers();
							   }

					       } );
					       suggestInProgress = false;
		                  },SUGGEST_DELAY
		                 );    // Ende zeitverzoegertes Ajaxen
		             }
			   }
			   else if(event.keyCode == 13 ||  event.keyCode == 38 ||  event.keyCode==40) {
		                 lockCursor('where_search');
		                handleArrow(event.keyCode);
		       }
		   }
	    });
	    $('form').submit(function(){

          if(!SUBMIT_CLICK){// || openSuggest!=""){
               return false;
          }
           else {
               openSuggest = "";
               if (ge('globalform') != null){
 		   ge('globalform').submit();
		}
           }
    });
    }
	if($.browser.version!="6.0"){
	   $('#content,#header,#footer').click(function(){closeAllLayers()});
	}
}

/* Array (tag1,tag2,....,tag10) &uumlbergeben*/


function fillWithContent(aContent){
    var html = new Array();
    var even_odd = new Array("even","odd");
    emptyContent();
    var topLimit = aContent.length - 1;
   	$('#'+openSuggest+' > div.suggest_inner > span').html( aContent[topLimit] );
    for(var i=0;i<topLimit;i++){
        html.push('<li class="'+even_odd[i%2]+'" id="suggest_what_tag_'+i+'"><a href="#" onmouseover="add_hover(this);" onmouseout="remove_hover(this);" onclick="applyTag(this.innerHTML);return false;">'+aContent[i]+'</a></li>');
    }
    $('#'+openSuggest+' ul').html(html.join(""));
}

function emptyContent(){
    $('#'+openSuggest+' ul').empty();
}


/** Implementiert die Pfeil Tasten Navigation
 * Keycodes
 * 13: Return
 * 37: left
 * 38: top
 * 39: right
 * 40: bottom
 */
function handleArrow(keyCode){
    if($('#'+openSuggest).size()<1)return;
    var entries = $('#'+openSuggest+' li').length;
    if(keyCode==40 && arrowCounter<entries-1){
        arrowCounter++;
        dehighlightArrow(arrowCounter-1);
    }
    else if(keyCode==38 && arrowCounter>-1){
        arrowCounter--;
        dehighlightArrow(arrowCounter+1);
    }
    else if(keyCode==13 && $('#'+openSuggest+' div.suggest_inner li.hover').size()>0){
        SUBMIT_CLICK =false;
        if($('#suggest_town').size()>0){  //Spezialfall Kartensuche, da anderes Format
            applyTag($('#'+openSuggest+' .suggest_inner ul .hover span.suggest_town_list_02').text());
        }
        else{
            applyTag($('#'+openSuggest+' div.suggest_inner ul li.hover a').text());
        }
    }
    highlightArrow(arrowCounter);
}

function applyTag(tag){
    if(openSuggest == "suggest_what"){
        $('#what_search').val(tag);
        if($('#suggest_choosed_what').size() == 1) {
        	$('#suggest_choosed_what').val(tag);
        }
        hideSuggest(openSuggest);
        //if( $('#where_search').val() != '' ) {
        //	executeSubmit();
        //}
    } else if(openSuggest == "suggest_where" ) {
        $('#where_search').val(tag);
        if($('#suggest_choosed_where').size() == 1) {
        	$('#suggest_choosed_where').val(tag);
        }
        hideSuggest(openSuggest);
        // console.log( $('#what_search').val() );
        if( $('#what_search').val() != '' ) {
        	executeSubmit();
        }
    }
    else if(openSuggest == "suggest_town"){
        if(tag.indexOf('suggest_what_tag')!=-1){ //tag ist hier kein tag, sondern die ID des Parent Links
            $('#where_search').val($('#'+tag+' span.suggest_town_list_02').html());
        }
        else{
            $('#where_search').val(tag);
        }
        saveMapSearchEntry(tag);

        hideMapSuggest();
        openSuggest = "";
    }
}

// Highlightet ein Tag
function highlightArrow(counter){
    $('#'+openSuggest+' .suggest_inner ul #suggest_what_tag_'+counter).addClass('hover');
}
//Dehighlightet ein Tag
function dehighlightArrow(counter){
    $('#'+openSuggest+' .suggest_inner ul #suggest_what_tag_'+counter).removeClass('hover');
}

function showSuggest(which){
    $('#'+which).show();
}

function hideSuggest(which){
    $('#'+which).hide();
    openSuggest = "";
    arrowCounter = -1;
}

function allowSubmit(){
    SUBMIT_CLICK = false;
}

function executeSubmit(){
     if (ge('executeVal')!==null) {
        ge('executeVal').value='Suchen';
    }
    if (ge('kindofsearchVal')!==null) {
     ge('kindofsearchVal').value='tradesearch'; /* ODS: Variable vor dem absenden setzen */
    }
    openSuggest='';
    allowSubmit();
    document.forms[0].submit();


}
/*ENDE Suggest*/

//Schliesst pauschal alle offenen Layer
var layers = Array('suggest_where','suggest_what','search_delimiter_branche','search_delimiter_details','tooltip_img_big','tooltip_info','search_delimiter_stadtteil','search_delimiter_place'); //Alle vorkommenden Layer als id
function closeAllLayers(exception){
    var topLimit = layers.length;
	for(var i=0;i<topLimit;i++){
        if(layers[i]!=exception)
            $('#'+layers[i]).hide();
    }
     if(ge('search_delimiter')!==null && $('.video_page').size()<1 && $('#search_delimiter .sel_inactive').size()<1){
        ge('toggler_branche').src ="../../static/img/site/arrow_open.gif";
        ge('toggler_details').src ="../../static/img/site/arrow_open.gif";
        ge('toggler_stadtteil').src ="../../static/img/site/arrow_open.gif";
        if (openFilter != 'place'){
            openFilter = "";
        }
    }
    if($('#toggler_place').length>=1){
     ge('toggler_place').src ="../../static/img/site/arrow_open.gif";
    }
    if(RADIALSEARCH && exception !='radial_search'){
        hide_radial_search();
    }
    if(exception != 'pers_bookmarking' && bookmark_out){
        disablePersBookmarking();
    }
    if(exception=="pers_bookmarking"){
        killAllTooltipSemaphores();
    }
    $('div.headersearch_error_line').show();
}

function killAllTooltipSemaphores(){
    window.clearTimeout(semaTimeoutTooltip);
    window.clearTimeout(semaTimeoutImgTooltip);
    window.clearTimeout(semaTooltip);
}

function resizeImgsAdvertPage(){
    $('img.toobig').ready(function() {
    	$('img.toobig').each(function() {
    		// var imageWidth = $(this).width();
    		if(this.complete) {
        		var imageWidth = this.width;
        		//console.log("resizeImgsAdvertPage:: "+imageWidth);
                if( imageWidth > 575) {
                	//console.log("resizeImgsAdvertPage:: imageWidth > 575");
                 	// $(this).css('width','575px');
                	this.width = 575;
                	//console.log("resizeImgsAdvertPage:: $(this).css('width','575px');");
                }
    		}
    	});
    });
}

/**
 * class TooltipDynHeightfactory for creating / initialisng TooltipDynHeight
 */
var TooltipDynHeightfactory = function() {
	this.callerClassName = null;
	this.callerIdInfix= '_';
	this.destinationIdPrefix = null;

	/**
	 * standard method gets all caller by class and sets ther tootip divs by given id prefix
	 * @return array of TooltipDynHeight
	 */
	this.getTooltipDynHeights = function() {
		var tooltipDynHeights = new Array();
		var caller = jQuery('.' + this.callerClassName);
		var ref = this;
		caller.each(function() {
			var callerId = this.id;
			var destinationId = callerId.split(ref.callerIdInfix);
			destinationId = destinationId[1];
			destinationId = ref.destinationIdPrefix + destinationId;
			tooltipDynHeights.push(new TooltipDynHeight('#'+callerId, '#'+destinationId));
		});
		return tooltipDynHeights;
	}
};

/**
 * class TooltipDynHeigh, used in Inseratsseite/Bewertung (eg Varta)
 * This class provides tooltips with dynamic height
 */
var TooltipDynHeight = function(callerSelector, destinationSelector, topPxOffset) {
	this.topPxOffset = topPxOffset !== undefined ? topPxOffset : 14;
	this.callerSelector = callerSelector !== undefined ? callerSelector : 'a.tooltip';
	this.destinationSelector = destinationSelector !== undefined ? destinationSelector : '#tooltipDiv';
	this.destinationCommonClassSelector = '.tooltipDynHeight';
	this.classPrefix = 'ttDynHeight_';
	this.classSuffix = '1';
	this.cssClass = this.classPrefix + this.classSuffix;
	this.listeningOnCaller = false;
	this.listeningOnDestination = false;
	this._timeout = null;
	var _this = this;

	this.getCssClass = function() {
		_this.cssClass = _this.classPrefix + _this.classSuffix;
		return _this.cssClass;
	};

	this.init = function() {
		var height = parseInt($(_this.destinationSelector).height());
		var lineHeight = parseInt($(_this.destinationSelector).css('line-height'));
		_this.classSuffix = "" + parseInt(height / lineHeight);
		$(_this.destinationSelector).addClass(_this.getCssClass());
		_this.startCallerListener();
	};

	this.startCallerListener = function() {
		_this.listeningOnCaller = true;
		$(_this.callerSelector).mouseover( function( event ) {
			window.clearTimeout(_this._timeout);
			_this.open();
			_this.updatePosition(event);
			_this.startDestinationListener();
		} );
		$(_this.callerSelector).mouseout( function( event ) {
			_this._timeout = window.setTimeout(function(){_this.close();},1500);
			return false;
		} );
		$(_this.callerSelector).mousemove( function( event ) {
			return false;
		} );
	};

	this.stopCallerListener = function() {
		_this.listeningOnCaller = false;

		$(_this.callerSelector).mouseover( function( event ) {
			return false;
		} );
		$(_this.callerSelector).mouseout( function( event ) {
			return false;
		} );
		$(_this.callerSelector).mousemove( function( event ) {
			return false;
		} );
	};

	this.startDestinationListener = function() {
		_this.listeningOnDestination = true;

		$(_this.destinationSelector).mouseover( function( event ) {
			if(_this._timeout !== null) {
				window.clearTimeout(_this._timeout);
			}
		} );
		$(_this.destinationSelector).mouseout( function( event ) {
			_this.close();
			_this.stopDestinationListener();
		} );
		$(_this.destinationSelector).mousemove( function( event ) {
			return false;
		} );
	};

	this.stopDestinationListener = function() {
		_this.listeningOnDestination = false;
		$(_this.destinationSelector).mouseover( function( event ) {
			return false;
		} );
		$(_this.destinationSelector).mouseout( function( event ) {
			return false;
		} );
		$(_this.destinationSelector).mousemove( function( event ) {
			return false;
		} );
	};


	this.open = function() {
		_this.closeAll();
		$(_this.destinationSelector).show();
	};

	this.close = function() {
		$(_this.destinationSelector).hide();
	};
	this.closeAll = function() {
		$(_this.destinationCommonClassSelector).hide();
	};

	this.updatePosition = function( event ) {
		var coords = getPageCoords( $(_this.callerSelector).attr('id') );

		// var topPos = coords.y - $(_this.destinationSelector).height();
		var topPos = coords.y + parseInt($(_this.callerSelector).height()) + 5;
		//var leftPos = ($.browser.msie && $.browser.version == "6.0") ? coords.x : coords.x;
		var leftPos = coords.x-19;

		$(_this.destinationSelector)
			.css("top",topPos + "px")
			.css("left",leftPos + "px");
	};
	this.init();
};
// End CLASS TooltipDynHeigh

//duf teaser wird nach dem Seitenload unten angeh&aumlngt
function duf_teaser(){
    var marginal_height =  $('#marginal').height()+$('#duf').height();
    if ( ge('duf')!= null && $('#maincontent').height()-70 >=  marginal_height){
         $('#duf').css("position","absolute");
	    var top = ge('maincontent').offsetHeight;
	    if($.browser.msie){
	       top = top+40;
	       var advert_top= top-35;

	    }
	    else{
	       top = top+40;
	       var advert_top= top-43;
	    }
	    if($('.video_page').size()>0){
	       	top = top - 30;
	       	advert_top= advert_top-32;
	       }
	    //keine Filter da
	    if($('#search_delimiter').size()<1){
	    	top = top - 66;
	       	advert_top= advert_top-66;
	    }
	    $('#duf').css("top",top+"px");
	    $('#advert_page #duf').css("top",advert_top+"px");
	    $('#duf').css("visibility","visible");
	    $('#duf').show();
    }
    else{
        $('#duf').css({"visibility":"visible","position":"static"});
        $('#duf').show();
    }
}

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

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

function clearSearchValue(){
		if ($('#what_search').attr('value') != null){
		  $('#what_search_overlay').css('background-image','none');
		}
		if ($('#where_search').attr('value') != null){
		  $('#where_search_overlay').css('background-image','none');
		}
}

// Hover bei der Haupt-Navi, speziell f&uuml;r den IE6
function initMainNavHover(){
	$("#main_nav a").mouseover(function(){
		if (this.className.indexOf('active')!=-1){
		}
		else{
		 // $('#'+this.id+' .main_nav_text').css('top', '4px');
		}
	});

	$("#main_nav a").mouseout(function(){
		if (this.className.indexOf('active')!=-1){
		}
		else{
		  $('#'+this.id+' span.main_nav_text').css('top', '9px');
		}
	});
}

function changeInputBg(element){

		$('#'+element.id+'_overlay').css('background-image','none');
}

function changeInputBgS(element){
	if ($('#'+element.id).attr('value') == null){
		$('#'+element.id+'_overlay').css('background-image','none');
		$('#'+element.id).attr('value','');
	}
}

function changeInputBgMS(element){
	if ($('#'+element.id).attr('value') == null){
		$('#'+element.id+'_overlay').css('background-image','none');
		$('#'+element.id).attr('value','');
	}
}

function changeInputBgM(element){
	if ($('#'+element.id).attr('value') == null){
		$('#'+element.id+'_inner').css('background-image','url("../../static/css/img/bg/bg_marginal_input_m.png")');
		$('#'+element.id).attr('value','');
	}
}

//Begin Radial Search

var RADIALSEARCH = false;
var radial_search_initialised = false;
/*
function initSlider(){
    if($.browser.msie)
    {
        ge('radial_anfasser').src ="../../static/img/icons/icon_anfasser.gif";
    }
   var dist= ge('inputDistance').value;
   if( dist>0){
        hide_radial_search();
        $('#radial_search_off').attr('src','../../static/img/btn/gs_aus_nor.png');
        $('#radial_search_on').attr('src','../../static/img/btn/gs_ein_act.png');
        //Alte Distanz uebernehmen
        ge('show_radial_distance').innerHTML = dist/1000;
        $('#show_radial .slider_indicator').css("left", calcRadialDistancePixel(dist)+"px");
        RADIALSEARCH = true;
    }
}
*/
function initSlider(){
	if(ge('inputDistance')===null)return;
    if($.browser.msie)
    {
    	try {
    		ge('radial_anfasser').src ="../../static/img/icons/icon_anfasser.gif";
    	} catch( e ) {}
    }
   var dist= ge('inputDistance').value;
   if( dist>0){
        hide_radial_search();
        $('#radial_search_off').attr('src','../../static/img/btn/gs_aus_nor.png');
        $('#radial_search_on').attr('src','../../static/img/btn/gs_ein_act.png');
        //Alte Distanz uebernehmen
        ge('show_radial_distance').innerHTML = dist/1000;
        $('#show_radial .slider_indicator').css("left", calcRadialDistancePixel(dist)+"px");
        RADIALSEARCH = true;
    }
}

function enableRadialSearch(){

	 if(!radial_search_initialised){
	    var t1 = ge('show_radial_distance');
	    var t2 = ge('inputDistance');
	    $('div.slider1').Slider({
	        accept : '.slider_indicator',
	        fractions : 100,
	        restricted: true,
	        onSlide : function( cordx, cordy, x , y){
	           t1.innerHTML = calcRadialDistance(((cordx)));
	           t2.value= 1000*calcRadialDistance(((cordx))); //Neu
	        }
	    });
	    radial_search_initialised = true;
    }
    closeAllLayers('show_radial');
    $('#radial_search_off').attr('src','../../static/img/btn/gs_aus_nor.png');
    $('#radial_search_on').attr('src','../../static/img/btn/gs_ein_act.png');
    $('#show_radial').bgiframe();
    $('#show_radial').css('display','block');
    $('#radial_picker').hide();

    if (ge('inputDistance').value == '-1')
    {
        ge('inputDistance').value = 3000;
    }


    ge('radial_target').innerHTML = ge('where_search').value;
    RADIALSEARCH = true;

}
function disableRadialSearch(){
	$('#radial_picker').hide();
	$('#show_radial').css('display','none');
    $('#radial_search_off').attr('src','../../static/img/btn/gs_aus_act.png');
    $('#radial_search_on').attr('src','../../static/img/btn/gs_ein_nor.png');
    ge('inputDistance').value=-1; // Neu

    RADIALSEARCH = false;
}

function close_radial_search(){
    $('#show_radial').hide();
}

function hide_radial_search(){
    close_radial_search()
    $('#radial_picker').show();
}

function show_radial_search(){
    closeAllLayers('show_radial');
    $('#show_radial').bgiframe();
    $('#show_radial').show();
    $('#radial_picker').hide();
     ge('radial_target').innerHTML = ge('where_search').value;
}
//Ende Radial Search

// Begin Filter Funktionen
var openFilter = "";
var timeoutetToggle = false;
var sema = "";
var sema2 = "";
var initialised = new Array();


function initFilter(which){
    openFilter = which;
    if(!is_initialised(openFilter)){
	    $('#delimiter_list_'+openFilter+' li a').each(function(){
	        $(this).click(function(){
	           if(openFilter=="branche")
	               applyFilterBranche(this);
	           else if(openFilter=="details")
                   applyFilterDetails(this);
               else if(openFilter=="stadtteil")
                   applyFilterStadtteil(this);
	           else if(openFilter=="place")
                   applyFilter('place', this);
	           return false;
	        }).mouseout(function(){
	           if(openFilter!="details")
	               remove_hover(this);
	           else
	               remove_hover(this.parentNode);
	           startTimeoutetCloseFilter(openFilter,'toggler_'+openFilter,8000);
	        }).mouseover(function(){
	           if(openFilter!="details")
	               add_hover(this);
	           else
	               add_hover(this.parentNode);
	           stopTimeoutetCloseFilter(openFilter);
	        });
	    });
	    initialised.push(openFilter);
	    if(openFilter="details"){
	       $('#delimiter_list_'+openFilter+' li input').each(function(){
	           $(this).mouseout(function(){remove_hover(this);startTimeoutetCloseFilter(openFilter,'toggler_'+openFilter,8000);}).mouseover(function(){add_hover(this);stopTimeoutetCloseFilter(openFilter);});
	       });
	    }
	}
	openFilter = "";
}

function is_initialised(which){
    var topLimit = initialised.length;
	for(i=0;i<topLimit;i++){
        if(which==initialised[i])
            return true;
    }
    return false;
}

function startTimeoutetToggleFilter(which,arrow,timeout){
    //arrow = ge(arrow);
    if(openFilter !=which){
        //offenen Filter sofort schliessen
	    if(openFilter!=="" && openFilter !=which){
	        close_filter(openFilter,arrow);
	    }
	    if(openFilter==="" ){
		    timeoutetToggle = true;
		    sema = window.setTimeout(function (){timeoutetToggleFilter(which,arrow)},timeout);
		}
    }
}

function startTimeoutetCloseFilter(which,arrow,timeout){
    //arrow = ge(arrow);
    if(openFilter ==which){
            timeoutetToggle = true;
            sema2 = window.setTimeout(function (){timeoutetToggleFilter(which,arrow)},timeout);
    }
}

function stopTimeoutetCloseFilter(){
	    timeoutetToggle = false;
	    window.clearTimeout(sema2);
}

function stopTimeoutetToggleFilter(which){
    if(openFilter !=which){
       timeoutetToggle = false;
       window.clearTimeout(sema);
    }
}

function timeoutetToggleFilter(which,arrow){
    if(timeoutetToggle)
        toggleFilter(which,arrow);
}

function close_filter(which,arrow){
    var arrow = ge(arrow);
    arrow.src = "../../static/img/site/arrow_open.gif";
    openFilter = "";
    $('#search_delimiter_'+which).hide();
    arrow.alt="Oeffnen";
    arrow.title="Oeffnen";

}

function open_filter(which,arrow){
    var heightlimit = 0;
    initFilter(which);
    var arrow = ge(arrow);
    closeAllLayers(openFilter);
    arrow.src = "../../static/img/site/arrow_close.gif";
    $('#delimiter_list'+which).hide();
    $('#search_delimiter_'+which).bgiframe();
    $('#search_delimiter_'+which).show();
    openFilter = which;

    //Scrollbar ja oder nein muss hier geschehen, da vorher keine h&oumlhe bekannt ist

 	if(which.indexOf('place')!=-1){
    	heightlimit = 295;
        initScroller(which,heightlimit);
    } else if(which.indexOf('branche')!=-1 || which.indexOf('stadtteil')!=-1 || which.indexOf('details')!=-1){
        heightlimit = 215;
        initScroller(which,heightlimit);
    } else {
        heightlimit = 215;
    }


 	/* alt
    if(which.indexOf('place')!=-1){
        heightlimit = 295;
        initScroller(which,heightlimit);


    }
    else
         heightlimit = 215;
    */


    //Refresh des Filter Footers, damit er richtig positioniert wird.
    $('div.search_delimiter_box_bottom').hide();
    $('div.search_delimiter_box_bottom').show();
    arrow.alt="Schliessen";
    arrow.title="Schliessen";
    $('#delimiter_list'+which).show();
}



function toggleFilter(which,arrow){
    timeoutetToggle = false;
    //Schliessen
    if(openFilter == which){
        close_filter(which,arrow);
    }
    //Oeffnen
    else{
        open_filter(which,arrow);
    }
}
function applyFilterBranche(dies){
    applyFilter('branche',dies);
}

function applyFilterDetails(dies){
    applyFilter('details',dies);
}

function applyFilterStadtteil(dies){
    applyFilter('stadtteil',dies);
}

function applyFilter(which,dies){
    var dots ="";
    if (which != 'place')
    {
    	var str = dies.firstChild.innerHTML;
    	if(which=="details")
         str = dies.innerHTML;
	    str = str.replace(/&amp;/g,"&");
	    if(str.length>18)
	        dots="...";
	    $('#selection_text_'+which).text(str.substring(0,17)+dots);
    }
    else
    {
    	var str = dies.lastChild.innerHTML;
    	if(which=="details")
            str = dies.innerHTML;
	    str = str.replace(/&amp;/g,"&");
	    if(str.length>40)
	        dots="...";
	    $('#selection_text_'+which).text(str.substring(0,39)+dots);
    }

    closeAllLayers(openFilter);
}
function resetFilter(which){
    $('#selection_text_'+which).html('nichts gew&auml;hlt');
    closeAllLayers(openFilter);
}

function applyFilterDetailsAll(dies){
    var str = "";
    var number = 0;
    $('#search_delimiter_scroll_02 input:checked').each(
        function(){
            if(number===0)
                str = $(this).next().children("a").text();
            number++;
        }
    );
    if(number>1)
        $('#selection_text_details').html(str.substring(0,14)+" und weitere");
    else if(number==1)
        $('#selection_text_details').html(str.substring(0,20));
    else
        resetFilter('details');
    closeAllLayers(openFilter);
    stopTimeoutetToggleFilter('details');
}

function resetFilterDetails(){
    closeAllLayers(openFilter);
    $('#selection_text_details').html('nichts gew&auml;hlt');
    $('#search_delimiter_scroll_02 input:checked').each(
        function(){
            this.click();
        }
    );
    $('#selection_text_details').html('nichts gew&auml;hlt');
}
// End Filter Funktionen

var MoveMediaNum;
var counter_left = 0, counter_right = 7;
var num_moves =0 // Anzahl der max Eintr�ge;
var size_mode = 0 // Bewegung in px;
var orig = ""; // 0=inseratsseite, 1=VC slider
var link_left,link_right =""; //handles f�r die scroll pfeile auf der VC Startseite
function initMoveMedia(){
    MoveMediaNum =  $('#media_scroller_content table tbody tr td').length; // Anzahl Elemente
    num_moves =7;
    size_mode = 73;
    orig = 0;
}

function initMoveMediaVideo(){
    MoveMediaNum =  $('#video_slider tbody tr td').length; // Anzahl Elemente
    counter_right = 20;
    num_moves =5;
    size_mode = 135;
    orig = 1;
    link_left = ge('link_scroll_left');
    link_right = ge('link_scroll_right');
}
var allowMediaSlide = true;

function moveMedia(element, dir,dies){
	if(allowMediaSlide){
		allowMediaSlide = false;
		var this_left = parseInt(ge(element).style.left.replace(/px/,""));
	    var new_left =0 ;
	    var move_size = size_mode;
	    if (dir =='left'){
	        if (counter_left >= 1){
	            new_left = 	this_left+move_size;
	            counter_left--;
	            counter_right++;
                if(orig==1){
                    if(counter_left+1==1){
                        dies.onmouseover = function(){};
                        dies.onmouseout = function(){};
                        v_dehover_slider(dies);
                        dies.firstChild.src = dies.firstChild.src.replace(/left(\.)/,"left_inact.");
                    }
                    else{
                        dies.onmouseover = function(){v_hover_slider(this);};
                        dies.onmouseout = function(){v_dehover_slider(this)};
                        dies.firstChild.src = dies.firstChild.src.replace(/_inact(\.)/,".");
                        // handle left
                        link_right.onmouseover = function(){v_hover_slider(this);};
                        link_right.onmouseout = function(){v_dehover_slider(this)};
                        link_right.firstChild.src = link_right.firstChild.src.replace(/_inact(\.)/,".");
                     }
                }
	        }
	        else{
	            new_left = 	0;
	            if(orig==1){
	               dies.onmouseover = function(){};
                    dies.onmouseout = function(){};
                    dies.firstChild.src = dies.firstChild.src.replace(/left(\.)/,"left_inact.");
	            }
	        }
	    }
	    else{
	        if(counter_left+ num_moves < MoveMediaNum){
	            new_left = 	this_left-move_size;
	            counter_left++;
	           counter_right--;
	           if(orig==1){
	               if(counter_left==MoveMediaNum-num_moves){
	                   dies.onmouseover = function(){};
                        dies.onmouseout = function(){};
                        v_dehover_slider(dies);
                        dies.firstChild.src = dies.firstChild.src.replace(/right(\.)/,"right_inact.");
	               }
    	           else{
        	           dies.onmouseover = function(){v_hover_slider(this);};
                       dies.onmouseout = function(){v_dehover_slider(this)};
                       dies.firstChild.src = dies.firstChild.src.replace(/_inact(\.)/,".");
        	           // handle left
                        link_left.onmouseover = function(){v_hover_slider(this);};
                        link_left.onmouseout = function(){v_dehover_slider(this)};
                        link_left.firstChild.src = link_left.firstChild.src.replace(/_inact(\.)/,".");
                   }
                 }
	        }
	        else{
	            new_left = 	this_left;
                //rechts ende
                if(orig==1){
                    dies.onmouseover = function(){};
                    dies.onmouseout = function(){};
                    dies.firstChild.src = dies.firstChild.src.replace(/right(\.)/,"right_inact.");

                }
	        }
	    }
	    jQuery('#'+element).animate({left:  new_left+"px",duration:500},function(){allowMediaSlide = true;});
	}
}

function changeMediaImg(element, content){
	element = $(element).children( 'a:not(.video_icon) img');
	element = element[0];

	var src = $( element.firstChild ).attr('src');
	var new_src= src.replace(/normal/, "red");
	$('#media_scroller_content table tbody tr td div a:not(.video_icon) img').each(function(e){
				var src_all = this.src;
				var new_src_all= src_all.replace(/red/, "normal");
				this.src = new_src_all;
			}
	);
	$( element.firstChild ).attr('src',new_src);
	$('#i_gallery_flash').html('<img src="'+ content +'" />');

	return false;
}

function changeMultiTab(element,wrapper, container){
	$('#multitab_container_'+wrapper+' .multitab_container').css('display','none');
	$('#multitab_container_'+wrapper+'_'+container).css('display','block');
	$('#multitab_container_'+wrapper+' .tabbed_nav li a').removeAttr('class');
	$(element).attr('class', 'active');
}

function toggleInserate(element){
	$('#duf').css("visibility","hidden");
	if($('#i_'+element+'_content').css('display') == 'none'){
		element_img = $('#i_'+element+'_headline img');
		element_img.attr('src','../../static/img/icons/icon_advert_minus.png').
					attr('title','schliessen').
					attr('alt','schliessen');
		$('#i_'+element+'_content').show();
	}
	else{
	    element_img = $('#i_'+element+'_headline img');
		element_img.attr('src','../../static/img/icons/icon_advert_plus.png').
					attr('title','oeffnen').
					attr('alt','oeffnen');
		$('#i_'+element+'_content').hide();
	}
    duf_teaser(); //muss mit springen
}

function add_hover(dies){
    $(dies).parent().addClass("hover");
}

function remove_hover(dies){
    $(dies).parent().removeClass('hover');
}

// Initialisierung des Tooltips in allen varianten
/**
 * @todo Refactor this. We need a generic tooltip functioniality for all types of tooltips. This is worth.
 */
var ALTTAG;
var TITLETAG;
var STATIC_URL ='../../static/img/';
var timeoutTooltip = false;
var currentTooltip = "";
var semaTimeoutTooltip = "";
var anotherTimeoutTooltip = '';
var semaTimeoutImgTooltip = "";

function startTimeoutShowTooltip(element){
    killAllTooltipSemaphores();
    hideTooltip(currentTooltip);
    //Fr den Rating Link kein alt-attribut
    if(element.id.indexOf('rating')!==-1){
	    ALTTAG = $(element).attr('alt');
	    $(element).attr('alt','');
    }
    TITLETAG = $(element).attr('title');
    $(element).attr('title','');
    semaTimeoutTooltip =window.setTimeout(function(){showTooltip(element)},TOOLTIP_DELAY);
}

function showTooltip(element){
     if(dragging)return;
     if(openFilter===""){
         closeAllLayers();
	     hideTooltipImg(currentTooltip);
	     window.clearTimeout(semaTimeoutTooltip);
	     if(!timeoutTooltip){
	        currentTooltip = element;
			$('#tooltip h3').html(TITLETAG);
			var coords =getPageCoords(element.id);
			var top = coords.y-50;
			var left = Math.round(coords.x +($(element).width()/2))-$('#tooltip h3').width()-4;
			var allOverWidth =$('#tooltip h3').width()+35 ;

				// ist der tooltip zu weit links ?
				if(coords.x-50<$('#tooltip h3').width()){
				  left = coords.x-18;
				  if($.browser.opera)
				  {
				      left =  left +2;
				   }
				  $('#tooltip_rev').css({"top":top+"px","left":left+"px","width":allOverWidth+"px"});
		          $('#tooltip_rev h3').html(TITLETAG);
				}
				else{
				  if($.browser.opera)
				  {
				      left =  left +2;
				   }
				  //Fr den Rating Link den tooltip etwas hher
				    if($(element).attr('id').indexOf('rating')!==-1){
				    	top=top-2;
				    }
				  $('#tooltip').css({"top":top+"px","left":left+"px","width":allOverWidth+"px"});
			    }
	    }
	    else{
	        window.setTimeout(function(){showTooltip(element);},1000);
	    }
	}
}
function hideCurrentTooltip(){
    hideTooltip(currentTooltip);
}

function hideTooltip(element){
    killAllTooltipSemaphores();
	if(element!==""){
		$('#tooltip').css({ top:'0px', left:'-1000px' });
		$('#tooltip_rev').css({ top:'0px', left:'-1000px' });
		if(typeof(element)!="object" && element.indexOf('tooltip_img_big_')!=-1){
		   $('#'+element).css({ top:'0px', left:'-1000px' });
		}

		if(typeof(element)!="object" && element.indexOf('img_info')!=-1){
		   $('#tooltip_img_info').css({ top:'0px', left:'-1000px' });
		}
		else if(typeof(element)=="object" && element.id.indexOf('info')!=-1){
	       $('#tooltip_info').css({ top:'0px', left:'-1000px' });
	       try {
	    	   // go to line 1656
	    	   $('#tooltip_another').css({ top:'0px', left:'-1000px' });
	       } catch( e ) {}
	    }
		element = $(element);
		//Fr den Rating Link kein alt-attribut
	    if(element.attr('id')!=null && element.attr('id').indexOf('rating')!==-1){
	    	element.attr('alt', ALTTAG);
	    }

		element.attr('title', TITLETAG);
		currentTooltip = "";
	}
}

function startTimeoutShowInfoTooltip(element){
    if(currentTooltip!=element){
	    hideTooltip(currentTooltip);
	    try {
	    	ALTTAG = $(element.firstChild).attr('alt');
	    	TITLETAG = $(element.firstChild).attr('title');
	    	$(element.firstChild).attr('title','').attr('alt','');
	    } catch( e ) {}
	    semaTimeoutTooltip =window.setTimeout(function(){showInfoTooltip(element)},TOOLTIP_DELAY);
	 }
}
function stopTimeoutShowInfoTooltip(){
    window.clearTimeout(semaTimeoutTooltip);
}
function showInfoTooltip(element){
    hideBranchenfinder();
     if(dragging)return;
     if(openFilter===""){
      window.clearTimeout(semaTimeoutTooltip);
         closeAllLayers();
         if(!timeoutTooltip){
            currentTooltip = element;
            try {
            	ALTTAG = $(element).attr('alt');
            	TITLETAG = $(element).attr('title');
            	$(element).attr('title','').attr('alt','');
            } catch( e ) {}
            var coords =getPageCoords(element.id);
            var top = coords.y-20;
            var left = coords.x +25;
            //if($.browser.opera || $.browser.msie)
            //          left =  left+15;
            $('#tooltip_info').css({"top":top+"px","left":left+"px"}).bgiframe().show();
        }
    }
}
// only used within Meine GelbeSeiten
function showAnotherTooltip(element) {
	hideBranchenfinder();
    if(dragging)return;
    if(openFilter===""){
     window.clearTimeout(anotherTimeoutTooltip);
        closeAllLayers();
        if(!timeoutTooltip){
           currentTooltip = element;
           try {
           	ALTTAG = $(element).attr('alt');
           	TITLETAG = $(element).attr('title');
           	$(element).attr('title','').attr('alt','');
           } catch( e ) {}
           var coords =getPageCoords(element.id);
           var top = coords.y-20;
           var left = coords.x - $('#tooltip_another').width() + 10;
           //if($.browser.opera || $.browser.msie)
           //          left =  left+15;
           $('#tooltip_another').css({"top":top+"px","left":left+"px"}).bgiframe().show();
       }
   }
}
function startTimeoutShowAnotherTooltip(element){
    if(currentTooltip!=element){
	    hideTooltip(currentTooltip);
	    try {
	    	ALTTAG = $(element.firstChild).attr('alt');
	    	TITLETAG = $(element.firstChild).attr('title');
	    	$(element.firstChild).attr('title','').attr('alt','');
	    } catch( e ) {}
	    anotherTimeoutTooltip =window.setTimeout(function(){showAnotherTooltip(element);},TOOLTIP_DELAY);
	 }
}
function stopTimeoutShowAnotherTooltip(){
    window.clearTimeout(anotherTimeoutTooltip);
}
//
var currentWebToolTipIndex = 0;
var currentWebToolTip = "";
function showWebToolTip(dies,index){
    hideWebToolTip(currentWebToolTip);
    var x_pos = xPos-480;
    var y_pos = yPos;
    var suffix = "_big_"+index ;
    var src = "";
    var url ="";
    currentWebToolTipIndex = index;
    if(dragging)return;
    closeAllLayers('tooltip_img_big_'+index);
    currentWebToolTip = 'tooltip_img_big_'+index;
    hideTooltipImg(currentTooltip);
      if(xPos<380){
         ge('tooltip_img_big_'+index).className = "tooltip_img_big_rev";

      }
      else{
          x_pos=x_pos+110;
          ge('tooltip_img_big_'+index).className = "tooltip_img_big";
      }
    if(currentTooltip == ""){
        ALTTAG = $(dies).attr('alt');
        TITLETAG = $(dies).attr('title');
        $(dies).attr('title','').attr('alt','');
        window.setTimeout(function(){determineTTCoords(dies,url,suffix,src,x_pos,y_pos);$('#tooltip_img_big_'+index).show();},50);
    }
}

function hideWebToolTip(element){
    $('#'+element).css({ 'top':'0px', 'left':'-1000px' });
}


//Zeigt den Tooltip plus ggf. den Link
function showTooltipImg(element,url,src){
    showTooltipImg(element,url,src, false);
}

function showTooltipImg(element,url,src, showUrl){
    //Dummy
    if(src=="dummy_polo.jpg"){
        src="../../test.png"
    }
    killAllTooltipSemaphores();
    var x_pos = xPos;
    var y_pos = yPos;
    if(dragging)return;
    hideTooltip(currentTooltip);
    closeAllLayers();
    if(currentTooltip != element){
        hideTooltipImg(currentTooltip);
    }
    if(currentTooltip == ""){
        var suffix ="";
        ALTTAG = $(element).attr('alt');
        TITLETAG = $(element).attr('title');
        var loading_gif = '<center><img src="../../static/img/icons/loading.gif" alt="loading" id="loading_gif" class="db" style="margin-top:45px" /></center>';
        $(element).attr('title','').attr('alt','');
        if(xPos<250){
           suffix = "_rev";
        }
        if(openFilter===""){
           window.clearTimeout(semaTooltip);
           if(!timeoutTooltip && currentTooltip===""){
              currentTooltip = element;
              if(url != "" && url.indexOf('http://')==-1)
                url="http://"+url;
              //$('#tooltip_img'+suffix+' h3').html('<a href="'+ url +'" target="_blank"><img src="'+ STATIC_URL +src+'" height="135" onmouseover="stopTimeoutTooltip()" onmouseout="startTimeoutTooltip();"/></a>');
              //Demo Implementierung eines uebergrossen test.jpg zum zeigen des loading.gifs
              $('#tooltip_img'+suffix+' h3').html(loading_gif+'<a href="'+ url +'" target="_blank"><img src="' + src + '" height="135" width="185" onmouseover="stopTimeoutTooltip()" onmouseout="startTimeoutTooltip();" style="display:none" id="new_tooltip_img"/></a>');
              if (showUrl) {
                semaTimeoutImgTooltip = window.setTimeout(function(){determineTTCoords(element,url,suffix,src,x_pos,y_pos)},TOOLTIP_DELAY);
              } else {
                semaTimeoutImgTooltip = window.setTimeout(function(){determineTTCoords(element,'',suffix,src,x_pos,y_pos)},TOOLTIP_DELAY);
              }
              $('#tooltip_img'+suffix+' h3 #new_tooltip_img').load(function(){
                 $('#loading_gif').remove();
                 $('#tooltip_img'+suffix+' h3 #new_tooltip_img').show();
              });
           }
        }
    }
}

function determineTTCoords(element,url,suffix,src,x_pos,y_pos){
     var coords =getPageCoords(element.id);

     if(element.className.indexOf('mousesensitive')!=-1){
        var top = coords.y -182;
        var left = x_pos-$('#tooltip_img'+suffix+' h3').width()-10;
     }
     else if(element.id.indexOf('web')!=-1){
        var top = coords.y -312;
        if(currentWebToolTipIndex != null && ge('tooltip_img_big_'+currentWebToolTipIndex) != null && ge('tooltip_img_big_'+currentWebToolTipIndex).className.indexOf('rev')!=-1)
            var left = x_pos+450;
        else
            var left = x_pos;
     }
     else{
         var top = coords.y-182;
         var left = Math.round(coords.x +($(element).width()/2))-$('#tooltip_img h3').width()-10;
    }
     if($.browser.opera)
        left =  left +0;

     if(suffix!=="" && suffix.indexOf("_big")==-1){
        left = x_pos -30;
     }
     if(url!==""){
       $('#tooltip_img'+suffix).addClass('url_tooltip'+suffix);
       short_url1 = url.substring(0,40);
       if (url.length<80) {
        short_url2 = url.substring(40,url.length);
       } else {
        short_url2 = url.substring(40,77)+'...';
       }
       $('#tooltip_img'+suffix+' h3').css('height','216px');
       $('#tooltip_img'+suffix+' #tooltip_link'+suffix).html(short_url1+'<br />'+short_url2);
       if(url.indexOf('http://')!=-1)
        ge('tooltip_link'+suffix).href=url;
       else
        ge('tooltip_link'+suffix).href="http://"+url;
       top = top-31;
     }
     if($('#wallpaper_ads_01').size()>0){
        top = top -100;
     }
     $('#tooltip_img'+suffix).css("top",top+"px").css("left",left+"px");
}

function hideTooltipImg(element){

	$('#tooltip_img').css({ 'top':'0px', 'left':'-1000px' });
	$('#tooltip_img_rev').css({ 'top':'0px', 'left':'-1000px' });
	$('div.tooltip_img_big').css({ 'top':'0px', 'left':'-1000px' });
     $('#tooltip_img').removeClass('url_tooltip');
     $('#tooltip_img_rev').removeClass('url_tooltip');
     $('#tooltip_img h3').css('height','186px');
     $('#tooltip_img_rev h3').css('height','186px');
     $('#tooltip_img_rev #tooltip_link_rev').html('');
     currentTooltip = "";
     timeoutTooltip = false;
	if(element!==""){
	     element = $(element);
	     element.attr('alt', ALTTAG);
	     element.attr('title', TITLETAG);
	}
}
var semaTooltip = "";
function startTimeoutTooltip(){
        if($('#tooltip_img').css('left') =="-1000px"){
            hideTooltipImg(currentTooltip);
            hideTooltip(currentTooltip);
            window.clearTimeout(semaTimeoutImgTooltip);
            window.clearTimeout(semaTimeoutTooltip);
            window.clearTimeout(semaTooltip);
        }
        else{
            semaTooltip = window.setTimeout("startHideTimeoutTooltip()",1300);
        }
        timeoutTooltip = true;
          currentTooltip = "";
}

function stopTimeoutTooltip(){
    timeoutTooltip = false;
}

function startHideTimeoutTooltip(){
    if(timeoutTooltip){
        hideTooltipImg(currentTooltip);
    }
}

//Liefert die Koordinaten eines Elements auf der Seite in Form eines Objekts
//Refactored by Ulf Tiburtius.
//@TODO Please test all old methods, whih use this method.
function getPageCoords (elementId) {
	var coords = {x: 0, y: 0};
	var element;
	// tell me, what this is good for?
	if (document.getElementById || $.browser.opera){
		element = document.getElementById(elementId);
	} else if (document.all) {
		element = document.all[elementId];
	}
	// new body
	var obj = element;
	var curleft = curtop = 0;
	if( obj.offsetParent ) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while ( obj = obj.offsetParent );
		coords.x = curleft;
		coords.y = curtop;
	}
	return coords;
     // the old body
     /*if (element) {
       do {
        if(element.currentStyle){
            if(element.currentStyle.position!='relative'){
                coords.x += element.offsetLeft;
                coords.y += element.offsetTop;
            }
        }
        else{
            coords.x += element.offsetLeft;
            coords.y += element.offsetTop;
        }
         element = element.offsetParent;
       }
       while (element)
       return coords;
     } else {
       return null;
     }*/
    }

function labelHover(element){
	$(element).css('font-weight','bold');
}

function labelDeHover(element){
	$(element).css('font-weight','normal');
}

/* Branchenfinder */

var semaBranchenfinder = "";
var f_timeoutShowBranchenfinder = false;
var f_timeoutHideBranchenfinder = false;
var currentBranchenfinder = "";
var firstBranchenfinder = ""; //ist links az oder rubrik
var leftOffset = 250; // Bei Zweispaltigkeit gibt es 2 Positionen. Eine linke und eine rechte. Dies hier ist der Grenzwert
var currentCat = ""; //HTML id der ausgew&aumlhlten Kategorie (cat_x)
var show_add_info = false;
var add_info_text = "";
var LEFT_OFFSET_SECOND_FINDER = -10;
var prologPos = "";


/**
 * Allgemeiner Branchenfinder Container
 */
var Branchenfinder = {


};

//Auslagerung der Events vom Markup hierher
function initBranchenfinderContents(){
    $('#finder_az ul li a').click(function(){
        buildSecondFinder(this.innerHTML.toLowerCase());
        showBranchenfinder('second',currentCat,'');
        return false;
    });
}

// von ODS geaendert (Mantis-Bugs 2015, 2033)
function isProlog( which ){
   if( which.length >= 7 && which.substr( 0, 6 ) == "prolog" )
      return true
   return false
}

function callBranchenfinder(which,dies,themenId,infoId){
    if(!documentLoaded)return;
    killAllTooltipSemaphores();
    if(currentTooltip!=="")
        hideCurrentTooltip();
    if(currentBranchenfinder!=="")
        hideBranchenfinder();
    var doAjax = false
    var wo = ""
    locationHitList = null
    if( which == "first" || which == "az" || which == "third" ){
        wo = getWoEingabe();
        if( wo != "" )
            doAjax = true
    }
    if( doAjax == true ){
	        determineBFCoords('prolog,'+which,dies);
	        $('#finder_prolog div.empty_notice').css('display','none');
	        $('#finder_prolog ul').empty();
	        $('#finder_prolog img.hide_branchenfinder_x').show();
			$('#finder_prolog').css('visibility','visible');
			$('#finder').show();
			$('#finder_prolog').show();
            $.getJSON(PATH_TO_LOCATIONHITS, {wo:wo }, function( data ){
            var anzahl = data.length;
            if( anzahl == 1 ){
                locationHitList = data
                locationHitIndex = 0
                $('#finder_prolog').hide();
                $('#finder_'+which).show();
                $('#finder_'+which).css('visibility','visible')
                determineBFCoords(which,dies);
                showBranchenfinder( which, dies, themenId, infoId )
            }else if( anzahl > -1 ){
                $('#finder_prolog div.finder_first_inner h2').show();
                locationHitList = data
                showBranchenfinder( 'prolog,'+which, dies, themenId, infoId )
            }else{
           }
        })
    }else{
         if(dies!=="" && which != "second")
            determineBFCoords(which,dies);
           $('#finder_'+which+' img.hide_branchenfinder_x').show();
		    $('#finder_'+which).css('visibility','visible');
		    //$('#finder').show();
		    //$('#finder_'+which).show();
        showBranchenfinder( which, dies, themenId, infoId )
    }
}

function recalibrateBranchenfinder(){
    $('#finder').css("top","94px");
}

//Von ODS um Parameter erweitert (Mantis-Bug 2003)
function showBranchenfinder(which,dies,themenId,infoId){
    if(which.indexOf('prolog')<0){

    }
     $('#finder_'+which+' div.scroll_content').css("top",'0px'); //scroll Position
    applyIVWBranchenfinder( which, dies, themenId, infoId); //IVW Aufruf, Rumpf definiert in defines.js
    // Block von ODS geaendert (Mantis-Bugs 2015, 2003)
    setWoInfo(which);
    if( isProlog( which ) ){
        firstBranchenfinder = which;
       if(locationHitList.length>0){
            buildLocations( which, dies, themenId, infoId) ;
       }
       else{
            $('#finder_prolog ul').empty();
          $('#finder_prolog .empty_notice').show();
       }
       $('#finder_prolog .loading_gif').css('display','none');
    }

    if(which=="first" || which == "az" || which == 'third'){
        firstBranchenfinder = which;
        if(which=="first" && ge(dies).parentNode.childNodes.length>2){
	        show_add_info = true;
	        add_info_text = dies.innerHTML;
	        if(which=="first" && show_add_info){
	            $('#finder_first .add_info_container .topic').html(add_info_text);
	        }else if(!show_add_info){
	            $('#finder_first .add_info_container .topic').html("");
	        }

	    }
	    else{
	        show_add_info = false;
	        add_info_text = "";
	    }
    }
    currentCat = dies;
    if(which=="first"){
    	$('#finder_prolog').hide();
    	$('#finder_first img.hide_branchenfinder_x').show();
        $('#finder_first').show().css('visibility','visible')
        buildRubriken(themenId);
        $('#finder_'+which+' img.loading_gif').css('display','none');
        //Block von ODS hinzugefuegt (Mantis-Bug 2033)
        $('#nuetzlicheInformationenHotelUndGastrononie').hide().css('visibility','hidden');
        $('#nuetzlicheInformationenGesundheitUndWellness').hide().css('visibility','hidden');
        if( infoId==1 ){
            $('#nuetzlicheInformationenHotelUndGastrononie').show().css('visibility','visible');
        }
        if( infoId==2 ){
            $('#nuetzlicheInformationenGesundheitUndWellness').show().css('visibility','visible');
        }
    }
    else if(which=="second"){

       $('img.hide_branchenfinder_x').hide();
       $('#finder').css("width","570px");

      if($.browser.mozilla && jQuery.browser.version.substr(0,3)=="1.8"){
         $('#finder_second *').css('overflow-y','auto');
         $('#finder_second .scroll_content').css('overflow-x','hidden');
       }
       $('#finder_second img.hide_branchenfinder_x').show();
       $('#finder_second').css('visibility','visible');
       $('#finder_'+which+' img.loading_gif').css('display','none');
    }
    else if(which=="third"){
        buildThirdFinder(themenId, infoId); //beim thirdfinder ist die themenId eigentlich eine RubrikenId
       $('#finder_'+which+' .loading_gif').css('display','none');
        $('img.hide_branchenfinder_x').hide();
        $('#finder_third img.hide_branchenfinder_x').show();
        $('#finder_third').css('visibility','visible');
    }
    else if(which == "az"){
        //fillAZ von ODS hinzugefuegt (Matis-Bug 2015)
        fillAZ(infoId);
       $('#finder_'+which+' img.loading_gif').css('display','none');
        $('img.hide_branchenfinder_x').hide();
        $('#finder_az .hide_branchenfinder_x').show();
        $('#finder_az').css('visibility','visible');
    }
	showButtonAndScrollers(which);
	if($.browser.msie && $.browser.version == "6.0"){
	    $('#finder_'+which).bgiframe();
	    $('#finder').bgiframe();
	}
	$('#finder').show();
    $('#finder_'+which).show();
    currentBranchenfinder = which;
}
function hideBranchenfinder(){
     $('#finder').hide();
    var p = $('#finder_prolog');
    var f = $('#finder_first');
    var s = $('#finder_second');
    var t = $('#finder_third');
    var a = $('#finder_az');

    $('#finder finder_prolog div.add_info_container').hide();
    p.css({'visibility':'hidden','display':'none'});
    $('#finder finder_first div.add_info_container').hide();
    f.css({'visibility':'hidden','display':'none'});
    $("#finder #finder_second div.error").hide();
    s.css({'visibility':'hidden','display':'none'});
    t.css({'visibility':'hidden','display':'none'});
    a.css({'visibility':'hidden','display':'none'});

    $('#finder #loading_gif_'+currentBranchenfinder).show();
    $('#finder div.empty_notice').hide();
    $('#finder div.error').hide();
    $('#finder div.hide_branchenfinder_x').hide();
    $('#finder').css("width","auto");
    if(currentBranchenfinder!=="")
        hideButtonAndScrollers(currentBranchenfinder);
    currentBranchenfinder = "";
    currentCat ="";

}

function hideButtonAndScrollers(which){
    if( isProlog( which ) )
        which="prolog"
    $('#finder #finder_'+which+' button').hide();
    $('#finder #finder_'+which+' h2').css('background-image','url()');
    //$('#finder #finder_'+which+' .finder_scroll').css('background-image','url()');
    if(which=="first")
        $('#finder_first div.add_info_container').hide();

}
function showButtonAndScrollers(which){
    if( isProlog( which ) )
        which="prolog";
    $('#finder_'+which+' button').show();
    $('#finder_'+which+' h2').css('background-image','url(../../static/css/img/bg/bg_dotted_line_black.png)');
    $('#finder_'+which+' div.finder_scroll').css('background-image','url(../../static/css/img/bg/bg_dotted_line_black.png)');
}

function determineBFCoords(which,dies){
    var firstItemCoords = getPageCoords('cat_1');
    var yPosOfFirstItem = firstItemCoords.y+12;
    var lessOfTopPosIfWallpaperAd = 109;

    if( $.browser.msie &&  $('#wallpaper_ads_01').size() >= 1 ) {
    	yPosOfFirstItem += lessOfTopPosIfWallpaperAd;
    }
    var yItem = Math.round((yPos - yPosOfFirstItem)/26)+1;
    // Extra-W�rste f�r Finder Gastro && Wellness
    yItem += ( $('#start_finder_list_gastro').size() == 1 ||  $('#start_finder_list_wellness').size() == 1) ? 1 : 0;
    yPosOfFirstItem -= ( $('#start_finder_list_gastro').size() == 1 || $('#start_finder_list_wellness').size() == 1 ) ? 26 : 0;

    var $finder = $('#finder');
    if(isProlog(which)){
        prologPos = yItem;
    } else if(!isProlog(which) && prologPos!==""){
        yItem = prologPos;
        prologPos = "";
    }
    // Ab 10 "Reihen" immer den selben BG (mit F�hnchen ganz unten) nehmen und tiefer setzen
    if(yItem>10){
    	var diesTop = ((yItem-10)*26)+176;
        $finder.css('top',diesTop+'px');
        yItem = 10;
    } else {
        y = yPosOfFirstItem-98;
    	if( $('#wallpaper_ads_01').size() >= 1 )  {
    		y = y - lessOfTopPosIfWallpaperAd;
    	}
        $finder.css('top',y+'px');
    }
    if(which=="az"){
        var coordsOfAZ = getPageCoords('cat_az');
        var xPosOfAZ = coordsOfAZ.x;
        x_pos = xPosOfAZ + $('#'+dies).width()+12;
		if(x_pos<290){
			BFSide = "left";
			x_pos = "81"; //fixe Position um �berlagerungen mit dem Werbeflash zu verhindern
		} else {
			BFSide ="right";
			x_pos = "285"; //fixe Position um �berlagerungen mit dem Werbeflash zu verhindern
		}
        y_pos = (coordsOfAZ.y-266);
        // set lower (??) if ads above
        if($('#wallpaper_ads_01').size() >= 1 && !$.browser.msie) {
        	y_pos = y_pos - lessOfTopPosIfWallpaperAd;
        }
        $finder.css('top',y_pos+'px').css('left',x_pos+'px');
    } else {
        var diesCoords = getPageCoords(dies);
        x_pos = diesCoords.x + $('#'+dies).width()+12;
		//Auf welcher Seite wurde der BF ge�ffnet ?
		if(x_pos<290){
			BFSide = "left";
			x_pos = "81"; //fixe Position um �berlagerungen mit dem Werbeflash zu verhindern
		} else {
			BFSide ="right";
			x_pos = "285"; //fixe Position um �berlagerungen mit dem Werbeflash zu verhindern
		}
        ge('finder_first').className= 'finder_first_'+yItem;
		ge('finder_third').className= 'finder_first_'+yItem;
		ge('finder_prolog').className= 'finder_first_'+yItem;
	    $finder.css('left',x_pos+"px");
    }
}

function applyBranchenfinderSingle(dies){
    hideBranchenfinder();
    document.forms[0].submit();
}

//released durch anwenden button
//zusaetzliches Validieren, ob >0 && <25 ausgew&aumlhlt wurde
function applyBranchenfinderAll(which){
     if($('#finder_'+which+' input:checked').length===0){
        showBranchenfinderError("mindes-<br/>tens 1 Branche",which)
     }
     else if($('#finder_'+which+' input:checked').length>BF_MAX_SELECTS){
         showBranchenfinderError("maximal<br/>25 Branchen",which)
     }
     else{
     	if (ge('kindofsearchVal')!==null) {
     		ge('kindofsearchVal').value='tradelistindex'; // Neu by ODS
   		}
        hideBranchenfinder();
        document.forms[0].submit();
     }
}

function showBranchenfinderError(error,which){
    $('#finder_'+which+' #errortext2_'+which).html(error);
        if($.browser.version != "6.0"){
            $("#finder_"+which+" .error").animate({
                opacity: "show",
                display: "block",
                duration:300
              });
        }
        else
            $('#finder_'+which+' .error').show();
}

function buildRubriken(currentCat){
    $('#finder_first ul').empty();
    $.getJSON(PATH_TO_RUBRIKEN, {themaID:currentCat,'locationHit':getLocationHit() },function (data){
           fillRubriken(data);
    });
}

var currentHoveredRubrik = "";
function handleRubrikhover(id){
   if(currentHoveredRubrik!=="")
    remove_hover(ge(currentHoveredRubrik));
   currentHoveredRubrik = id;
}

function removeRubrikhover(dies){
    if(dies.id!=currentHoveredRubrik){
        remove_hover(dies);
    }
}
function fillRubriken(data){
  //   data = "";
    $('#finder_first div.empty_notice').hide();
    var neww =  new Array();
     if(data.length!=0 && data!==""){
    	var topLimit = data.length;
	    for(var i=0;i<topLimit;i++){
	       var onclick = "handleRubrikhover(this.id);this.onmouseout=null;buildSecondFinder('"+data[i][1]+"');showBranchenfinder('second',this.id);return false;"
	       neww.push('<li><a href="#" id="rubrik_'+data[i][1]+'" onclick="' +onclick+ '" onmouseover="add_hover(this);this.onmouseout=function(){removeRubrikhover(this);};" onmouseout="removeRubrikhover(this);">'+data[i][0]+'</a></li>');
	    }
	    var html = neww.join("");
	    $('#finder_first ul').html(html);
	    neww = null;
	 }
	 else{
	      hideButtonAndScrollers('first');
	      $('#finder_first div.empty_notice span.noticetext2').html($('#where_search').val());
          $('#finder_first div.empty_notice').show();
          //$('#finder_first').show();
	 }
}
// Funktion von ODS hinzugefuegt (Mantis-Bug 2060
function buildSecondFinder(rubrikId){
	$('#finder div.error').hide();
    var parameter = {'rubrikId' : rubrikId, 'locationHit':getLocationHit() }
    buildSecondFinderDo( parameter )
}
// Funktion von ODS hinzugefuegt (Mantis-Bug 2060
function buildSecondFinderAZ(letter, infoId){
    var parameter
    if( infoId == 1 )
       parameter = {'buchstabe' : letter, 'at':'gg', 'locationHit':getLocationHit() }
    else if( infoId == 2 )
       parameter = {'buchstabe' : letter, 'at':'wg', 'locationHit':getLocationHit() }
    else
       parameter = {'buchstabe' : letter, 'locationHit':getLocationHit() }
    buildSecondFinderDo( parameter )
}
// Funktion von ODS hinzugefuegt (Mantis-Bug 2060
function buildSecondFinderDo(parameter){
    $('#finder_second ul').empty();
    $.getJSON(PATH_TO_BRANCHEN, parameter, function (data){
           fillSecondFinder(data);
           //checkBFScroller('second');
    });
}
// Funktion von ODS hinzugefuegt (Mantis-Bug 2060)
function afterAZ( letter ){
      buildSecondFinderAZ( letter )
      showBranchenfinder('second')
}
// Funktion von ODS ge�ndert (Mantis-Bug 2424)
function fillSecondFinder(data){
    var tradename = "";
    var tradeid = "";
    var toAppend = new Array();
    $('#finder_second div.empty_notice').hide();
    if(data.length!=0){
    	var topLimit = data.length;
        for(var i=0;i<topLimit;i++){
          //toAppend von ODS angepasst (Mantis-Bug 2040)
          tradename = data[ i ][ 0 ]
          tradeid = data[ i ][ 1 ]
         toAppend.push(getBranchenEintrag( tradename, tradeid,i ));
         }
         $('#finder_second ul').html(toAppend.join(""));
         toAppend = null;
         $('#finder_second ul li a').mouseover(function(){add_hover(this.parentNode);}).mouseout(function(){remove_hover(this.parentNode);}).click(function(){applyBranchenfinderSingle(this);return false;});
         $('#finder_second input').mouseover(function(){add_hover(this);}).mouseout(function(){remove_hover(this);});
      }
      else{
          hideButtonAndScrollers('second');
          $('#finder_second .'+firstBranchenfinder+' span.noticetext2').html($('#where_search').val());
          $('#finder_second .'+firstBranchenfinder).show();
      }
}

 function buildThirdFinder(rubrikId, infoId){
    var parameter;
    if( infoId == 1 )
       parameter = {'rubrikId':rubrikId, 'at':'gg', 'locationHit':getLocationHit() }
    else if( infoId == 2 )
       parameter = {'rubrikId':rubrikId, 'at':'wg', 'locationHit':getLocationHit() }
    else
       parameter = {'rubrikId':rubrikId, 'locationHit':getLocationHit() }
    $('#finder_third ul').empty();
    $.getJSON(PATH_TO_BRANCHEN, parameter,function (data){
           fillThirdFinder(data);
     });
}

// Funktion von ODS geaendert (Mantis-Bug 2424)
function fillThirdFinder(data){
    $('#finder_third div.empty_notice').hide();
    var neww = new Array();
    var tradename = "";
    var tradid = "";

    if(data.length!=0){
    	var topLimit = data.length;
        for(var i=0;i<topLimit;i++){
          tradename = data[ i ][ 0 ]
          tradeid = data[ i ][ 1 ]
          neww.push(getBranchenEintrag( tradename, tradeid,i ));
        }
        $('#finder_third ul').html(neww.join(""));
        neww = null;
        $('#finder_third  ul li a').mouseover(function(){add_hover(this.parentNode);}).mouseout(function(){remove_hover(this.parentNode);}).click(function(){applyBranchenfinderSingle(this);return false;});
        $('#finder_third input').mouseover(function(){add_hover(this);}).mouseout(function(){remove_hover(this)});
      }
      else{
          hideButtonAndScrollers('third');
          $('#finder_third div.empty_notice').show();
      }

}

//Funktion von ODS geaendert (Mantis-Bugs 2069)
function getBranchenEintrag( tradename, tradeid,i ){
    var saf_style='';
    if($.browser.safari){
        saf_style =' style="top:-5px"';
    }
    var toAppend = "";
    toAppend+='<li class="clearfix"><input type="checkbox" name="trade" value="' + tradeid + '" id="' + getFinderJsId( i ) + '" onmouseover="add_hover(this);" onmouseout="remove_hover(this)" ';
    toAppend+='class="v_middle" '+saf_style+'/><label for="finder_val_'+i+'"><a href="#" onclick=afterTradeList("' + escape(tradename) + '","' + i + '",0,"' + (data.length-1)+'");return false;>'+tradename+'</a></label></li>';
    return toAppend;
}

//Funktion von ODS geaendert (Mantis-Bugs 2015, 2040)
function setWoInfo(which){
   if( isProlog( which ) )
      return;

   var bundesweit = "bundesweit"
   var wo = bundesweit
   if( locationHitList != null )
       wo = locationHitList[locationHitIndex][1];

   if(which=="first" || which=="third" || which == "az" ){
       $('#branchenfinder_wo_0').html(wo);
       if( wo != bundesweit )
           setWoEingabe( wo )

   }
   if(which == 'second'){
       $('#branchenfinder_wo_1').html(wo);
       $('#branchenfinder_wo_2').html(wo);
   }
   if(which == 'third'){
       $('#branchenfinder_wo_3').html(wo);
       $('#branchenfinder_wo_4').html(wo);
   }
}


//Funktion von ODS geaendert (Mantis-Bugs 2015, 2033)
function buildLocations( which, dies, themaId, infoId ){
   $('#finder_prolog ul').empty();
   fillLocations(which, dies, themaId, infoId);
}

//Von ODS geaendert (Mantis-Bugs 2015, 2033)
function fillLocations(which, dies, themaId, infoId){
    $('#finder_prolog div.empty_notice').hide();
    var  nextWhich = which.substr( 7, which.length - 7 );
    var old = $('#finder_prolog ul').html();
    var neww = new Array();
    var onclick = "";
    var topLimit = locationHitList.length;
    for(var i=0;i<topLimit;i++){
           onclick = "showWithLocation('" + nextWhich + "','" + dies + "','" + themaId + "','" + infoId + "','" + i + "');return false;";
           neww.push('<li><a href="#" onclick="' + onclick + '">'+locationHitList[i][1]+'</a></li>');
    }
    $('#finder_prolog ul').html(neww.join(""));
    neww = null;
    $('#finder_prolog ul li a').mouseover(function(){add_hover(this);}).mouseout(function(){remove_hover(this);});
}


//Von ODS geaendert (Mantis-Bugs 2015, 2033) Funktion "showRubriken" entfaellt und wird durch die Funktion "showWithLocation" ersetzt
function showWithLocation( which, dies, themaId, infoId, locationHitIndex_ ){
  locationHitIndex = locationHitIndex_
  hideBranchenfinder();
 showBranchenfinder( which, dies, themaId, infoId )
}
function getLocationHit(){
   if( locationHitList == null )
      return "";
   return locationHitList[ locationHitIndex ][ 0 ]
}
function getWoEingabe(){
   var wo = $('#where_search').val();
   if( wo == null )
       wo = "";
   return wo;
}

//Funktion von ODS hinzugefuegt (Mantis-Bug 2015)
function fillAZ(infoId){
    $('#branchen_finder_a_m').empty();
    $('#branchen_finder_n_z').empty();
    var parameter;
    if( infoId == 1 )
       parameter = {'rubrikId' : '', 'at' : 'gg', 'locationHit':getLocationHit() }
    else if( infoId == 2 )
       parameter = {'rubrikId' : '', 'at' : 'wg', 'locationHit':getLocationHit() }
    else
       parameter = {'rubrikId' : '', 'locationHit':getLocationHit() }

    $.getJSON(PATH_TO_BRANCHEN, parameter,function (data){
        if(data.length!=0){
            var s = data[0]
               fillLetterToId( 'A', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'B', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'C', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'D', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'E', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'F', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'G', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'H', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'I', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'J', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'K', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'L', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'M', s, infoId, 'branchen_finder_a_m' )
               fillLetterToId( 'N', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'O', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'P', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'Q', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'R', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'S', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'T', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'U', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'V', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'W', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'X', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'Y', s, infoId, 'branchen_finder_n_z' )
               fillLetterToId( 'Z', s, infoId, 'branchen_finder_n_z' )
        }
     });


}
//Funktion von ODS hinzugefuegt (Mantis-Bug 2015)
function fillLetterToId(letter, letters, infoId, id){
   var id_ = '#' + id
   var old = $(id_).html()
   var activ = true;
   if( letters.indexOf( letter ) < 0 )
       activ = false;

   var s = "<li"
   if( activ == false )
       s = s + ' class="inactive"'
   s = s + "><span>"
   if( activ == true ){
       s = s + '<a href="#" id="' + letter + ''+infoId+'" onclick="afterAZ('
       s = s + "'" + letter + "'"
       s = s + ",'" + infoId + "'"
       s = s + ');handleAZhover(this.id);this.onmouseout=null;return false;" onmouseover="add_hover(this.parentNode);this.onmouseout=function(){removeAZhover(this);}"  >'
   }
   s = s + letter
   if( activ == true ){
       s = s + '</a>'
   }
   s = s + "</span>"
   $(id_).html(old+""+s)
}

var currentHoveredAZ = "";
function handleAZhover(id){
   if(currentHoveredAZ!=="")
    remove_hover(ge(currentHoveredAZ).parentNode);
   currentHoveredAZ = id;
}

function removeAZhover(dies){
    if(dies.id!=currentHoveredAZ){
        remove_hover(dies.parentNode);
    }
}

//Funktion von ODS hinzugefuegt (Mantis-Bug 2040)
function getFinderJsId( i ){
   var id = "finder_val_" + i
   return id
}
//Funktion von ODS hinzugefuegt (Mantis-Bug 2040)
function afterTradeList( tradename, index, index_min, index_max ){
   var tradename = unescape(tradename);
   var i = index_min
   var id
   //erst alle auf false
   while( i <= index_max ){
       id = getFinderJsId( i )
       ge( id ).checked = false
       i ++
   }

   if (ge('kindofsearchVal')!==null) {
     ge('kindofsearchVal').value='tradelistindex'; // Neu by ODS
   }

   //dann die Gewaehlte auf true
   id = getFinderJsId( index );
   ge( id ).checked = true;

   //Uebername der ausgewaehlten Branche ins was-Feld
   var reg=new RegExp("(\\d+)","g");
   var erg=reg.exec( tradename);
   if (erg.index>0) {
	   // Trefferzahl des Branchenfinder abschneiden
	   $('#what_search').focus().val( tradename.substr(0, erg.index-1));
   } else {
	   $('#what_search').focus().val( tradename );
   }
}
//Funktion von ODS hinzugefuegt (Mantis-Bug 2040)
function setWoEingabe( wo ){
   $('#where_search').val( wo )
}

//END

/* Ende Branchenfinder */
/* Start Merkzettel */
var countBookmarkingContent = 0;
var idsInBookmark = new Array();
var bookmark_out = false;
var oldTitle = "";
var bookmarkScrollInitialised = false;
var temp = 0;

function togglePersBookmarking(){
    if (bookmark_out){
        disablePersBookmarking();
    }
    else{
        enablePersBookmarking();
    }
}

function disablePersBookmarking(){
    ge('pers_bookmarking').style.overflow = "hidden";
    $('#pers_bookmarking').animate({left:  '-480px'});
    bookmark_out = false;
}

function enablePersBookmarking(){
    ge('pers_bookmarking').style.overflow = "visible";
    closeAllLayers('pers_bookmarking');
    $('#pers_bookmarking').bgiframe().
    					   animate({left:  '0px'});
    bookmark_out = true;
}
function shakeBookmarking(){
    ge('pers_bookmarking').style.overflow = "hidden";
    $('#pers_bookmarking').animate({
        marginLeft:"5px",
        duration: 100
    });
    $('#shade').animate({
        opacity:"0.5",
        duration: 100
    });

    window.setTimeout(function(){$('#pers_bookmarking').animate({marginLeft:"0px", duration: "fast" });},300);
    window.setTimeout(function(){$('#shade').animate({opacity:"0.0", duration: "fast" });},300);
}

// mode = 0 : element add per click
// mode = 1 : element add per drop
function iAddToBookmarking(dies,mode){
    var resultId = ge('maincontent').className;

	if(in_BookmarkArray(resultId))
	        return;
	shakeBookmarking();
    var currentTitle    = $('h1 span').html();
    var currentAddress  = $('#advert_location p #inserat_addr_str').html().replace(/(<([^>]+)>)/gi,", ");
        currentAddress += ", "+$('#advert_location p #inserat_addr_ort').html().replace(/(<([^>]+)>)/gi,", ");
    currentAddress = currentAddress?currentAddress:"";//bedingter Ausdruck um auf null zu pruefen
    var currentTel      = "Tel: "+$('#advert_location_communication .tel1').html()?"Tel: "+$('#advert_location_communication .tel1').html():"";
    var currentFax      = "Fax: "+$('#advert_location_communication .fax').html()?"Tel: "+$('#advert_location_communication .tel1').html():"";
    var even_odd        = $('#pers_bookmarking_content_scroll .clearfix').length%2===0?'even':'odd';
    $('img.enabledIcon').parent().hide();
    $('img.disabledIcon').show().
    					  fadeTo("slow",0.5); // Ausgrauen des Ikons
    insertIntoBookmarking(currentTitle,currentAddress,currentTel,currentFax,even_odd,resultId);
}

// mode = 0 : element add per click
// mode = 1 : element add per drop oder video thickbox
function addToBookmarking(dies,mode){
    if(mode===0)
        var resultId        = "result_"+dies.firstChild.id.substring(dies.firstChild.id.indexOf('_')+1,dies.firstChild.id.lastIndexOf('_'));
    else if(mode==1)
        var resultId = dies;
    if(in_BookmarkArray(resultId))
        return;
    shakeBookmarking();

    $('#dragHelper').css("border","1px solid pink");
    if(mode===0){
        $(dies).hide();
        $('#'+resultId+' img.disabledIcon').show();
        $('#'+resultId+' img.disabledIcon').fadeTo("slow",0.5); // Ausgrauen des Ikons
    }
    else{
        $('#'+dies+' img.enabledIcon,#TB_video_merker img.enabledIcon').parent().hide();
        $('#'+dies+' img.disabledIcon,#TB_video_merker img.disabledIcon').show();
        $('#'+dies+' img.disabledIcon,#TB_video_merker img.disabledIcon').fadeTo("slow",0.5); // Ausgrauen des Ikons
    }
    var currentTitle    = $('#'+resultId+' a.hit_result_title').html();
    var currentAddress  = $('#'+resultId+' p.hit_result_address').html()?$('#'+resultId+' .hit_result_address').html():""; //bedingter Ausdruck um auf null zu pruefen
    var currentTel      = $('#'+resultId+' p.hit_result_tel').text()?$('#'+resultId+' .hit_result_tel').text():"";//bedingter Ausdruck um auf null zu pruefen
    var currentFax      = $('#'+resultId+' .hit_result_fax').html()?$('#'+resultId+' .hit_result_fax').html():"";//bedingter Ausdruck um auf null zu pruefen
    var even_odd        = $('#pers_bookmarking_content_scroll .clearfix').length%2===0?'even':'odd';
    insertIntoBookmarking(currentTitle,currentAddress,currentTel,currentFax,even_odd,resultId);
}

//Anderungen von ODS 09. Sep 2008
function gotoDetailPage( resultIdWithPrefix ){
//bsp: http://localhost/yp/advertisement.yp?subscriberID=128013788368-1014
    var id = resultIdWithPrefix.substring("result_".length, resultIdWithPrefix.length);
    var l = '/yp/advertisement.yp?subscriberID='+id
    location = l;
}

function insertIntoBookmarking(currentTitle,currentAddress,currentTel,currentFax,even_odd,resultId){
    insertIntoBookmarkingDo(currentTitle,currentAddress,currentTel,currentFax,even_odd,resultId,true,true);
}

var newDiv = "";
function insertIntoBookmarkingDo(currentTitle,currentAddress,currentTel,currentFax,even_odd,resultId,last,doAddToCookie){
    if( countBookmarkingContent >= MERKZETTEL_MAX )
       return;
    countBookmarkingContent++;
    ge('number_entries_img').src = ge('number_entries_img').src.replace(/num.*gif/,'num_'+countBookmarkingContent+".gif");
    if($.browser.msie)
        ge('number_entries_img').style.marginTop = "5px";
    $('#number_entries').html(countBookmarkingContent);
    $('#string_entries_1').show();
    var onclick = "gotoDetailPage( '" + resultId + "' );return false;"
    onclick = 'onclick="' + onclick + '"'
    newDiv = newDiv + '<div class="even clearfix">'+
                    '<input type="checkbox" class="checkbox_entry" id="v_'+resultId+'" />'+
                    '<div class="pers_b_entry">'+
                    '<h2><a href="#" ' + onclick + '>'+currentTitle+'</a></h2>'+
                        '<p>'+currentAddress+'</p>'+
                        '<p><span style="float:left;">'+currentTel+'</span><a href="#"' + onclick + ' class="underline float_r">Mehr Informationen</a><br class="clearall" /></p>'+
                        '<p>'+currentFax+'</p>'+
                    '</div>'+
                    '<br class="clearall" />'+
                '</div>';
    if( last == true ){
        $('#pers_bookmarking_content_scroll').append(newDiv);
        $('#number_entries').html(countBookmarkingContent);
        $('#pers_bookmarking_content_inner .selectAll').show();
        if(countBookmarkingContent==1){
            $('#string_entries_2').show();
            $('#string_entries_1').hide();
        }
        else{
            $('#string_entries_1').show();
            $('#string_entries_2').hide();
        }
        $('#pers_bookmarking_content .zero_notice').hide();
        $('#pers_bookmarking_content .bookmarking_buttons').show();
        newDiv = "";
    }
    idsInBookmark.push(resultId);

    //Keksen
    if( doAddToCookie == true )
       addToCookie(resultId);
}

function addToCookie(resultId){
     if($.cookie(COOKIE_NAME)===null)
        var currentKeks = "";
    else
        var currentKeks = $.cookie(COOKIE_NAME)+",";
    $.cookie(COOKIE_NAME,unescape(currentKeks)+''+resultId, { path: '/', expires: 10 });
}

function selectAll(dies){
   if(dies.checked)
    $('#pers_bookmarking_content_scroll input:checkbox').attr("checked","checked");
   else
    $('#pers_bookmarking_content_scroll input:checkbox').attr("checked","");
}


function deleteSelected(){
   countBookmarkingContent = $('#pers_bookmarking_content_scroll input.checkbox_entry').length-$('#pers_bookmarking_content_scroll input.checkbox_entry:checked').length ;
   if($('#advert_page').length>0){
	    $('img.disabledIcon').hide();
	    $('img.enabledIcon').parent().show();
   }
    $('#pers_bookmarking_content_scroll input.checkbox_entry:checked').each(function(){
        //this.id muss ein praefix gefolgt von "_" haben
        deleteFromBookmarkArray(this.id.substring(this.id.indexOf('_')+1,this.id.length));
        deleteFormCookie(this.id.substring(this.id.indexOf('_')+1,this.id.length));
        currentId = this.id.substring(this.id.lastIndexOf('_')+1);
        $('#result_'+currentId+' .disabledIcon').hide();
        $('#result_'+currentId+' ul li a:hidden').show();
       });
   $('#pers_bookmarking_content_scroll input.checkbox_entry:checked').parent().remove();
   $('#checkAll').attr("checked","");
   if(countBookmarkingContent>0){
        $('#number_entries').html(countBookmarkingContent);
        if(countBookmarkingContent==1){
	        $('#string_entries_2').show();
	        $('#string_entries_1').hide();
	    }
	    else{
	        $('#string_entries_1').show();
	        $('#string_entries_2').hide();
	    }
        $('#pers_bookmarking_content_inner div.selectAll').show();
        $('#pers_bookmarking_content div.zero_notice').hide();
        $('#pers_bookmarking_content div.bookmarking_buttons').show();
    }
    else{
        $('#number_entries').html('keine');
        $('#string_entries_2').hide();
        $('#string_entries_1').show();
        $('#pers_bookmarking_content_inner div.selectAll').hide();
        $('#pers_bookmarking_content div.zero_notice').show();
        $('#pers_bookmarking_content div.bookmarking_buttons').hide();
    }

   ge('number_entries_img').src = '../../static/img/icons/notice/num_'+ countBookmarkingContent +'.gif';
   $('#number_entries').html(""+countBookmarkingContent);
   SUBMIT_CLICK = false;
}

function saveSelected() {
   alert( "Save leaflet." );
}

function deleteFromBookmarkArray(which){
    var newIdsInBookmark = new Array();
    var new_index = 0;
    var topLimit = idsInBookmark.length;
    var tmp;
    for(i=0;i<topLimit;i++){
        if(idsInBookmark[i]!=which){
            newIdsInBookmark[new_index++]=which;
        }
    }
    idsInBookmark = newIdsInBookmark;
}

function deleteFormCookie(id){
     var currentKeks = $.cookie(COOKIE_NAME);
     var ext = "";
     //gibt es ein leading _, dann entfernen (Fuer die Testcases)
     if(id.charAt(0)=="_"){
        ext = '/,?'+id.substring(1,id.length)+'/g';
     }
     else{
        ext = '/,?'+id+'/g';
     }
     currentKeks = currentKeks.replace(eval(ext),"");
     //Falls der erste Eintrag geloescht wurde, muss jetzt das komma an currentKeks[0] geloescht werden
     if(currentKeks.charAt(0)==","){
        currentKeks = currentKeks.substring(1,currentKeks.length);
     }
     $.cookie(COOKIE_NAME,unescape(currentKeks), { path: '/', expires: 10 });
}

function in_BookmarkArray(elem){
	var topLimit = idsInBookmark.length;
    for(var i=0;i<topLimit;i++){
        if(idsInBookmark[i]==elem)
            return true;
    }
    return false;
}
function dropBookmark(which){
    if(which.className.indexOf('search_hit')!=-1){
        addToBookmarking(which.parentNode.parentNode.id,1);
    }
}
function iDropBookmark(which){
        iAddToBookmarking(which.parentNode.id,1);
}

//IE6 Notwendiges, konkret soll hiermit position:fixed simuliert werden
var lastX=-1;
var semaFixPos = "";
function truebody(){
    return (document.compatMode!="BackCompat")? document.documentElement : document.body
}

function fixPos(){
    lastX = truebody().scrollTop;
    document.getElementById("pers_bookmarking").style.left = "-550px";
    temp = getPageCoords('content');
    yOffset = temp.y;
    //Bei Wallpapern weiter runter
    if ( $('#wallpaper_ads_01').size() >= 1)
        yOffset = yOffset + 110;
    if(semaFixPos===""){
        semaFixPos = window.setTimeout(function(){
        if(lastX != truebody().scrollTop){
            fixPos();
        }
        else{
            window.clearTimeout(semaFixPos);
            semaFixPos = "";
            document.getElementById("pers_bookmarking").style.top = (truebody().scrollTop+yOffset)+"px";
            //document.getElementById("pers_bookmarking").style.left = "-480px";
            $('#pers_bookmarking').animate({
                left: "-480px",
                duration: "slow"
            });
        }
        },1500);
     }
}

/* Ende Merkzettel */
/* Being Sortier Layer */
var semaSort = "";
var sort_out = false;
var f_timeoutetSort = false;
function disable_result_sorts(){
    $('img.sort_pulldown_img').attr('src','../../static/img/site/arrow_open.gif');
    $('div .sort_pulldown').hide();
}

function toggle_result_sort(dies){
    f_timeoutetSort = true;
    closeAllLayers();
    hideTooltip(currentTooltip);
    stopTimeoutShowSort(dies);
    var src = "";

    if(dies.parentNode.parentNode.parentNode.id.indexOf('header')!=-1){
        src = 'content_header';
        counterpart = 'content_footer';
    }
    else{
        src = 'content_footer';
        counterpart = 'content_header';
    }

    disable_result_sort(counterpart);

    if($('#'+src+' div.sort_pulldown').css('display')=='block'){
        $('#'+src+' img.sort_pulldown_img').attr('src','../../static/img/site/arrow_open.gif');
        $('#'+src+' div.sort_pulldown').css('display','none');
        if($.browser.msie) {$('#result_0 .hit_result_tel img').css('visibility','visible');}
    }
    else{

        $('#'+src+' .sort_pulldown_img').attr('src','../../static/img/site/arrow_close.gif');
        if($.browser.msie) {$('#result_0 .hit_result_tel img').css('visibility','hidden');}
        $('#'+src+' .sort_pulldown').bgiframe();
        $('#'+src+' .sort_pulldown').css({'display':'block','z-index':'99'});
    }
}


function disable_result_sort(which){
     $('#'+which+' div.sort_pulldown').hide();
     $('#'+which+' img.sort_pulldown_img').attr('src','../../static/img/site/arrow_open.gif');
}

function applySort(dies){
    $('#content_footer a.current_sort_crit').html(dies.innerHTML);
    $('#content_header a.current_sort_crit').html(dies.innerHTML);
    disable_result_sorts();
}

function startTimeoutShowSort(dies){
    f_timeoutetSort = true;
    semaSort = window.setTimeout(function(){timeoutetShowSort(dies);},1500);
}

function stopTimeoutShowSort(dies){
    window.clearTimeout(semaSort);
    semaSort = "";
    sort_out = false;
    f_timeoutetSort = false;
}

function timeoutetShowSort(dies){
    if(semaSort!=="" && f_timeoutetSort){
        toggle_result_sort(dies);
    }
}
/* Ende Sortierlayer*/
/* Begin Email Formulario */
//von ods geaendert (Mantis-Bug 2042)
function checkForm(){
	var errors = "";
	if (ge('email_add').value===""){
		errors = errors + "&email_add_error=1";
	}
	if (ge('your_name').value===""){
		errors = errors + "&your_name_error=1";
	}
	if (ge('email_message').value===""){
		errors = errors + "&email_message_error=1";
	}
	if (errors.length == ""){
		document.forms[0].submit();
	}
	else{
		window.location.href = location.href + errors;
        return false;
	}
}
/* End Email Formulario */

// Oeffnen der Thickbox, berechnen der Position etc,
function openThickbox(element, entryid )
{
	var TB_WIDTH = $('#' + element + '_TBinner').width();
	var TB_HEIGHT = $('#' + element + '_TBinner').height();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("#TB_overlay_messageLayer").click(closeThickbox(element));
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){

				$("#TB_overlay_messageLayer").click(closeThickbox(element));
			}
		}

	var pagesize = tb_getPageSize();
	var page_x = pagesize[0] - 150;
	var page_y = pagesize[1] - 150;

	$('#TB_overlay_messageLayer').height(document.body.offsetHeight).bgiframe().show();
   // $('#' + element + '_TBinner').css({marginLeft: '-' + parseInt(( TB_WIDTH / 2),10) + 'px'});

	//if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
	//	$('#' + element + '_TBinner').css({marginTop: '-' + parseInt(( TB_HEIGHT / 2 +40),10) + 'px'});
	//}
	if( "undefined" != entryid || null != entryid ) {
		try {
			$( '#form_' + element + ' #entryid' ).val(entryid);
		} catch( e ) { }
	}

    $('#' + element + '_TBinner').show();
}


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

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


function openPopUp(element, entryid )
{
	switch(element)
	{
		case 'mobilesportal':
		var popup = window.open('../popups/GS_mobilesportal.php?type=mobilesportal', 'GelbeSeiten', "width=638,height=640,left=100,top=150");
		break;

		case 'click_to_call':
		var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=638,height=590,left=100,top=150");
		break;

		case 'email_versenden':
		if($.browser.msie){
		  var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=643,height=698,left=100,top=150");
		}
		else
		  var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=638,height=688,left=100,top=150");
		break;

		case 'oepnv':
		var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=800,height=748,left=0,top=0,scrollbars=yes");
		break;

		case 'stadtplan_inseratseite':
		var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=800,height=748,left=0,top=0,resizable=yes");
		break;

		case 'anb':
		var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=800,height=748,left=0,top=0,scrollbars=yes");
		break;

		case 'hrs':
		var popup = window.open('../popups/GS_'+element+'.php?type='+element, 'GelbeSeiten', "width=800,height=748,left=0,top=0,scrollbars=yes");
		break;

		case 'inserat':
		var popup = window.open('../inserate/GS_inseratseite_print.php', 'GelbeSeiten', "width=658,height=590,left=100,top=150,scrollbars=yes");
		break;

		case 'ergebnis':
		var popup = window.open('../ergebnisliste/GS_ergebnisliste_print.php', 'GelbeSeiten', "width=658,height=590,left=100,top=150,scrollbars=yes");
		break;

		case 'ergebnis_video':
		var popup = window.open('../ergebnisliste/GS_ergebnisliste_video_print.php', 'GelbeSeiten', "width=625,height=590,left=100,top=150,scrollbars=yes");
		break;

		case 'meinmerkzettel':
			if( "undefined" == entryid || null == entryid ) {
				return false;
			} else {
				var popup = window.open('../global/g_merkzettel_print.php?entryid=' + entryid, 'GelbeSeiten', "width=658,height=590,left=100,top=150,scrollbars=yes");
			}
			break;
		case 'merkzettel':
		var popup = window.open('../global/g_merkzettel_print.php', 'GelbeSeiten', "width=658,height=590,left=100,top=150,scrollbars=yes");
		break;
	}
	popup.focus();
}

function sendInnerForm() {
	if( 0 == arguments.length ) return;
	var n = $( '#' + arguments[0] );
	var elements = $( '#' + arguments[0] + ' input, #' + arguments[0] + ' textarea' );
	var l = elements.length;
	var f = $( '#inner-form');
	var fs = document.createElement( 'fieldset' );
	try {
		while( l-- ) {
			var node = elements.get(l).cloneNode( true );
			fs.appendChild( node );
		}
		f.get(0).appendChild( fs );
		f.get(0).submit();
	} catch( e ) {}
}

function displayFormularError( elementid, formlabels ) {
	try {
	$( '#' + elementid + ' p.warning_bg_none' ).show();
	} catch( e ) {}
	if( "undefined" == formlabels || null == formlabels || '' == formlabels ) return;
	var tmp = formlabels.split( ',' );
	if( tmp.length == 0 ) {
		tmp = 'error-' + tmp;
	} else {
		tmp = 'error-' + tmp.join( ' error-' );
	}
	tmp += ' error-form';
	$( '#' + elementid ).addClass( tmp );
}

function toggle( selector, target, replace1, replace2 ) {
	hideCurrentTooltip();
	try {
		$( selector ).toggle();
		var tmp = $( '#' + target ).get(0).innerHTML;
		if( tmp == replace1 ) {
			$( '#' + target ).get(0).innerHTML = replace2;
		} else {
			$( '#' + target ).get(0).innerHTML = replace1;
		}
	} catch( e ) {}
}

function saveSearch() {
	// collect your form data e.g. sessionid, search-form fields or generated searchstring-id for a result-list. whatever you do, guy, I have no idea - dunno your backend.
	var callback = function( e ) {
		/** @todo IE 6 breaks apart */
		$('.save-result-list').each( function() {
			this.innerHTML = '<span>gespeichert</span> <img src="../../static/img/icons/icon-search-saved.png"  alt="Suche gespeichert" title="Suche gespeichert" class="margin_t_0  search-icon" />';
		} );
		
	};
	$.ajax( {
		type: "post",
		url: "../../jsp/ajax/save_search.php",
		data: "name=John&location=Boston",
		async:false,
		success: callback,
		error: function(e) { alert(e); }
	} );
	return false;
}

function adjustWindow(x,y){
 	window.resizeTo(x,y);
}

var mapSuggestOffsetTop = 0;
var mapSuggestViewport = 0;
var global_start = 0;
var global_offset = 0;

//Kartensuggest Begin
function  initMapSuggest(){
    var firstTimeOpen = true;
    if(ge('suggest_town').className.indexOf('enable')==-1 || $('#suggest_town li').size()<1){
        return;
    }
    else{
         ge('where_search').focus();
         $('#suggest_preview #mapSuggestResults').html($('#suggest_town li').size());
         $('#suggest_preview').show();
         $('#where_search').keydown(function(event){
                openSuggest = "suggest_town";
        });
    }

    $('form').submit(function(){
          if(openSuggest!==""){
               return false;
          }
           else {
               openSuggest = "";
               ge('globalform').submit();
           }
    });
}

function initAndShowMapSuggest(){
	showMapSuggest();
        temp = getPageCoords('suggest_what_tag_0');
        mapSuggestOffsetTop = temp.y -15;
        mapSuggestViewport = $('#suggest_town div.scroll_container').height();
}

var currentMapSearchItem = 0;
function saveMapSearchEntry(id){
    currentMapSearchItem = id.substring(id.lastIndexOf('_')+1,id.length);

}

function showMapSuggest(){
	//ausgewaehltes Item festellen
	$('#suggest_town_list li').each(function(){
	    if(this.firstChild.id.substring(this.firstChild.id.lastIndexOf('_')+1,this.firstChild.id.length)==currentMapSearchItem){
	        this.firstChild.style.fontWeight = "bold";
	    }
	    else{
	        this.firstChild.style.fontWeight = "normal";
	    }
	});

	ge('where_search').focus(); // Damit die Pfeilnavi auch beim Mouseclick funktioniert.
	$('#suggest_preview').hide();
	$('#suggest_town').css({"visibility":"hidden","display":"block"}); //hack, damit die Hoehe schon vorher gelesen werden kann.
	$('#suggest_town').css("visibility","visible");
	$('#suggest_town').bgiframe().show();
	 openSuggest = "suggest_town";
}

function hideMapSuggest(){
    $('#suggest_town').hide();
    $('#suggest_preview').show();
    openSuggest = "";
}


/**
 * TagClouds Control
 * @return TagCloud
 */
var TagCloud =  {
	elementClassName: 'tagcloud_element',

	init: function() {
		if( jQuery('.'+this.elementClassName).size() ) {
			$('.'+this.elementClassName+' .tc_middle').hide();
			$('.'+this.elementClassName+' .tc_less').hide();
			var ref = this;
			$('.'+this.elementClassName+' .tc_lower a').click(function() {
				ref.toggle();
				return false;
			});
		}
	},

	toggle: function() {
		if($('.'+this.elementClassName+' .tc_middle').css('display') == 'none') {
			$('.'+this.elementClassName+' .tc_middle').slideDown('slow');
			$('.'+this.elementClassName+' .tc_less').show();
			$('.'+this.elementClassName+' .tc_more').hide();
		} else if($('.'+this.elementClassName+' .tc_middle').css('display') == 'block') {
			$('.'+this.elementClassName+' .tc_middle').slideUp('slow');
			$('.'+this.elementClassName+' .tc_less').hide();
			$('.'+this.elementClassName+' .tc_more').show();
		}
	}
};

/**
 * Accordion Control
 */
var Accordion =  {
	_init : function() {
		$( '.p-toggle .toggle-btn' ).each(
			function( index ) {
				$( this ).bind( 'click',
								function() {
									Accordion._toggle();
									$.event.trigger( 'toggleIndicator' );
									return false;
								} );
				if( this.className.indexOf( 'toggle-indicator' ) != -1 ) {
					$( this ).bind( 'toggleIndicator', function( event ) {
						this.className = ( this.className.indexOf( 'expanded' ) != -1 ) ? this.className.replace( /expanded/, 'contracted' ) : this.className.replace( /contracted/, 'expanded' );
					} );
				}

			}
		);
	},

	_toggle : function() {
		$( ' .toggle-inner' ).each(
			function() {
				if( $( this ).css( 'display' ) == 'none' ) {
					//$( this ).slideDown( 'slow' );
					$(this).show();
					$( this ).parent().children( '.hide-on-click' ).hide();
				} else if( $( this ).css( 'display' ) == 'block' ) {
					//$( this ).slideUp( 'slow' );
					$(this).hide();
					$( this ).parent().children( '.hide-on-click' ).show()
				}
			}
		);
	}
};

var SimpleListAccordion = {

	init: function() {
		$('ul.simepleAccordion').hide();
		$('ul.simepleAccordion:first').show();
		$('ul.simepleAccordion li a').click( function() {
			var checkElement = $(this).next();
		    if( (checkElement.is('ul')) && (checkElement.is(':visible')) ) {
		    	return false;
		    }
		    if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
		    	$('#menu ul:visible').slideUp('normal');
		    	checkElement.slideDown('normal');
		    	return false;
		    }
		});
	}
};


/**
 * Little Thickbox Layer
 *
 * You can give a function that sets the position of domElem
 * or an array with [0]=>position,[1]=>left, [2]=>top
 * the function must take the domElem as Param
 *
 * @param domHTMLElem domElem
 * @param num width
 * @param num height
 * @param FUNCTION || array pos
 *
 */
var Overlay = function(domElem, width, height, pos) {
	this.domElement = domElem;
	this.width = width !== undefined ? width : null;
	this.height = height !== undefined ? height : null;
	this.pos = pos !== undefined ? pos : null;
	var ref = this;
	// Register CloseHandler
	jQuery(this.domElement).find('.close').click(function(event) {
		jQuery(ref.domElement).hide();
		return false;
	})

	this.setPosition = function() {
		var ref = this;
		if(this.pos == null) {
			return false;
		}
		if(jQuery.isFunction(this.pos)) {
			return this.pos.call(this,this.domElement);
		} else if(jQuery.isArray(this.pos)) {
			jQuery(ref.domElement).css( {
				position: ref.pos[0],
				left: ref.pos[1],
				top: ref.pos[2]
			} );
			return true;
		} else {
			return false;
		}
	}
}


// DOCUMENT READY
$(document).ready(function(){
	TagCloud.init();
	Accordion._init();
	if(jQuery('#poll_overlay_1').size()) {
		var overlayPoll = new Overlay(ge('poll_overlay_1'));
		jQuery(overlayPoll.domElement).show();
	}
	if(jQuery('#poll_overlay_2').size()) {
		var overlayPoll = new Overlay(ge('poll_overlay_2'));
		jQuery(overlayPoll.domElement).show();
	}

	//Video Community Detailseite Sprung zum Video Anker
	if(jQuery('#video_detail_page').size()>0){
		location.href = "#i_gallery_headline";
	}

	init_noscript();
    $('#pers_bookmarking').show();
	 os = navigator.platform.toLowerCase();
   isMac = os.indexOf('mac')>-1 || os.indexOf('apple')>-1;
	init_inputOnclickColorValues();
	if(ge('what_search')!==null ){
	         clearSearchValue();
	}
	var bodyClass = "";
	if(typeof($('body').attr('class'))=="string")
	   bodyClass=$('body').attr('class');

	if(ge('what_search')!==null && $('body').attr('id').indexOf('product')==-1 && $('body').attr('id').indexOf('privat')==-1 && bodyClass.indexOf('produktsuche')==-1 && bodyClass.indexOf('privat')==-1 && $('#map_search').size()<1 ){
	   initSuggest();
	}

    if(bodyClass != "print_page" && $('body').attr('id').indexOf('popup')<0){
	    //Radial Search freischalten
	   activateRadialSearch();
     }
    initBrowserChanges();
    $('.video_page img.btn_play').css('display', 'block');

    if ( $('#media_scroller').size() >= 1){
		initMoveMedia();
	}

	if ( $('#hit_table').size() >= 1){
		initMoveMediaVideo();
	}

	//wenns ein wallpaper gibt, alles zurechtr�cken
	if ( $('#wallpaper_ads_01').size() >= 1){
		initWallpaper();
		recalibrateBranchenfinder();
	}

	//wenn es keine Filter gibt, ebenfalls
	if($('#search_delimiter').size()<1){
		$('#pers_bookmarking').css('top','203px')
	}

	//Kartensuchsuggest initialisieren
	if($('#map_search').size()>0 && $('body').attr('id').indexOf('popup')<0){
	   initMapSuggest();
	}


	if($('#main_nav').length>0){
    initPreloader();
   }

   if($('#finder').length>0){
    initBranchenfinderContents();
    $('#marginal,#header,#footer').click(function(){hideBranchenfinder();});
   }
    //IE verz�gern, damit Init erst abgearbeitet werden kann
   if($.browser.msie && $.browser.version=='6.0'){
		window.setTimeout("initPosRelevantsItems()",5000);
		window.setTimeout("init_persbookmarking()",8000);
	}
	else{
		initPosRelevantsItems();
		init_persbookmarking();
	}
    //BF Komponenten IE6 schneller laden, da die eher geklickt werden
   if($.browser.msie && $.browser.version=='6.0'){
	   $("ul.start_finder_list a").mouseover(function(e){
	       xPos =e.pageX;
	       yPos =e.pageY;
	  });
    }
     //IE6 Autoscout ausblenden der Scroller
   if(!$.browser.msie && $.browser.version!='6.0'){
	   $("#autoscout_iframe").attr('scrolling', 'auto');

    }


	if($('#map').length>0){
    	initMap();
	}

	if($('div.scroll_content').length>0 && $('div.tooltip_img_big').length>0){
	   $('#maincontent, #marginal,#header,#footer').click(function(){hideTooltip('webToolTip');hideTooltipImg(currentTooltip);  hideCurrentTooltip(); });
	}

	//Print Seiten bekommen alle Links deaktiviert.
	if($('body.print_page').size()>0){
	   $('#maincontent a, div.draggable').css('cursor','default');
	   $('#maincontent div.print_tb').css("height",$('#maincontent').height());
	}


	 if($.browser.safari){
        $("div.mobile_portal button").css("left","0px");
        $("#btn_freecall").css("left","0px");
     }
	if($('body.print_page').size()<1 && $('#show_suggest').size()>0){
		if(ge('show_suggest').checked){
			SUGGEST_ENABLED = true;
		}
		else{
			SUGGEST_ENABLED = false;
		}
	}
	configureFlash();
	//Filter freischalten
	enableFilters();
	//zu grosse Bilder auf der Inseratsseite ?
	if($('#advert_page').size()>0) {
		// console.log("$('#advert_page').size()");
		resizeImgsAdvertPage();
	}
	documentLoaded = true;
	// AD Treatment. Ganz am Ende Iframe ajaxen und groesse auslesen/anpassen
	handleAds();
	//window.setTimeout(function(){ handleAds();},3000);
});