/* 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();
	$('#finder_first div.empty_notice').hide();
    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 a.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+' a.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){
    	   
           // Der Branchenfinder wurde aufgerufen, als eine unklare Eingabe im Ortsfeld stand
    	   if(dies == "cat_az"){
    		   logWipeActionByName('A-Z Ortsliste');
    	   } else {
    		   logWipeActionByName('BranchenFinder Ortsliste');
    	   }

           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 a.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"){

       $('a.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 a.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');
        $('a.hide_branchenfinder_x').hide();
        $('#finder_third a.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');
        $('a.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('+urlPrefix+'static/css/img/bg/bg_dotted_line_black.png)');
    $('#finder_'+which+' div.finder_scroll').css('background-image','url('+ urlPrefix +'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;

    /*
     * Ploetzlich im IE nicht mehr zu gebrauchen......
    if( $.browser.msie &&  $('#wallpaper_ads_01').size() >= 1 ) {
    	yPosOfFirstItem += lessOfTopPosIfWallpaperAd;
    }
    */
	var ot = absTop(ge(dies));
    var yItem = Math.round((ot - 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('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
		}
        if(yItem >0)
			ge('finder_first').className= 'finder_first_'+ yItem;
		else 
			$('#finder_first').hide();
		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;"
	              
	       // Bei einem Klick auf eine Rubrik soll das in die Statistik eingehen
	       onclick = "logWipeActionByName('BranchenFinder Branchenauswahl');" + onclick;
	       
	       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)" ';
    
    var onclick = 'afterTradeList("' + escape(tradename) + '","' + i + '",0,"' + (data.length-1)+'");return false;';   
    toAppend+='class="v_middle" '+saf_style+'/><label for="finder_val_'+i+'"><a href="#" onclick='+onclick+'>'+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="'
       
       // Bei einem Klick auf eine Rubrik soll das in die Statistik eingehen
       s = s + 'logWipeActionByName(\'A-Z alle Branchen Branchenauswahl\');'
       
       s = s + '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 */
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){
	var px = 60;
	if (dist<10000) {
		px = dist/80;
	}
	if (dist==10000) {
		px = 130;
	}
	if (dist==20000) {
		px = 150;
	}
	if (dist==30000) {
		px = 160;
	}
	if (dist==40000) {
		px = 170;
	}
	if (dist==50000) {
		px = 180;
	}
	return parseInt( px );
}



//Begin Radial Search

var RADIALSEARCH = false;
var radial_search_initialised = false;

function initSlider(){
	if(ge('inputDistance')===null)return;
    if($.browser.msie)
    {
    	try {
    		ge('radial_anfasser').src = urlPrefix + "static/img/icons/icon_anfasser.gif";
    	} catch( e ) {}
    }
   var dist = ge('inputDistance').value;
   if( dist>0){
        hide_radial_search();
        $('#radial_search_off').css('background-position','-600px -50px');
        $('#radial_search_on').css('background-position','-600px -150px');
        //Alte Distanz uebernehmen
        ge('show_radial_distance').innerHTML = dist/1000;
        var px = calcRadialDistancePixel( dist );
        $('#show_radial .slider_indicator').css("left", px+"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').css('background-position','-600px -50px');
    $('#radial_search_on').css('background-position','-600px -150px');
    $('#show_radial').bgiframe();
    $('#show_radial').css('display','block');
    $('#radial_picker').hide();

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


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

}
function disableRadialSearch(){
	$('#radial_picker').hide();
	$('#show_radial').css('display','none');
    $('#radial_search_off').css('background-position','-600px 0px');
    $('#radial_search_on').css('background-position','-600px -100px');
    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;
}

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);
    }

}
//Ende Radial Search/* Begin Search and Suggest */
/**
 * GelbeSeiten Suche mit Suggest
 *
 */
var Search = {

	// Some Constants
	KEYCODE: {
		left:	37,
		top:	38,
		right:	39,
		bottom: 40,
		tab:	9,
		enter:	13,
		escape:	27,
		space:	32,
		shift: 	16
	},

	// DOM Elements CSS Path prefixes/infices
	fieldNames: [ 'what' , 'where' , 'where_advert' ],

	// Timeout for suggest callback in milliseconds
	suggestDelay: 500,

	// Template for suggest entry as list element
	suggestEntryTemplate: '<li class="%%class%%" id="suggest_%%fieldName%%_tag_%%id%%"><a href="#">%%text%%</a></li>',

	// Hold current states of Searchform and Suggest here
	state: {
		suggestEnabled: true,
		// fieldName of currently running request or null
		suggestRequestRunning: null,
		// fieldName of currently opened suggest field, or null.
		suggestResponseFieldOpened: null,
		// The window.setTimeout-Resource of delayed XHR in suggest
		delayedSuggestTimeout: null,
		// index and input fieldName oof currently highlighted element of suggest output list
		currentHighlightedElement: { fieldName: null, index: -1 },
		preventFormSubmit: false
	},

	/**
	 * Init the search form with suggest
	 */
	init: function() {
		// Debug.log( "init::Search.state.suggestEnabled " + Search.state.suggestEnabled );
		if( Search.state.suggestEnabled ) {
			this.setHandlers();
			$( '.suggest' ).bgiframe();
		}
	},

	/**
	 * sets all handlers, the suggest needs
	 */
	setHandlers: function() {
		this.Handlers.setKeyDownHandlerForField( 'what' );
		this.Handlers.setKeyDownHandlerForField( 'where' );
		this.Handlers.setSuggestFieldHandlers();
		this.Handlers.setBlurHandlerForField( 'what' );
		this.Handlers.setBlurHandlerForField( 'where' );
		this.Handlers.setFocusHandlerForField( 'what' );
		this.Handlers.setFocusHandlerForField( 'where' );
		this.Handlers.setFormSubmitHandler();
		$( '.suggest .close' ).click( function() {
			var fieldName = this.parentNode.id.split( 'suggest_' )[1];
			Search.closeSuggestFieldByFieldName( fieldName );
		} );

		$( '#search_go' ).focus( function() {
			Search.closeAllSuggestFields();
		} );
	},

	/**
	 * Subclass Handlers which contains all handler methods
	 * for search and suggest
	 */
	Handlers: {

		/**
		 * The handler sumbit which can test some
		 * conditions and inject some action or prevent the
		 * form submit
		 * Currentyl the form must not be submitted if a
		 * suggestfield is opened
		 * @param {object} event the original passed event object
		 */
		setFormSubmitHandler: function( event ) {
			$( document.forms[0] ).submit( function() {
				if( Search.state.suggestEnabled ) {
					var dbgMesh = "Form wird ";
					dbgMesh += Search.state.preventFormSubmit ? "nicht " : "";
					dbgMesh += "abgesendet!";
					Debug.log( dbgMesh );
					Debug.log( "preventFormSubmit " + Search.state.preventFormSubmit );
					return false == Search.state.preventFormSubmit;
				} else {
					return true;
				}
			} );
		},

		/**
		 * Focushandler for given fieldName
		 * @param String fieldName
		 */
		setFocusHandlerForField: function( fieldName ) {
			Search.getInputForFieldName( fieldName ).focus( Search.Handlers._focusHandler );
		},

		/**
		 * Blurhandler for given fieldName
		 * @param String fieldName what|where
		 */
		setBlurHandlerForField: function( fieldName ) {
			Search.getInputForFieldName( fieldName ).blur( Search.Handlers._blurInputFieldHandler );
		},

		/**
		 * Keydown Handler for inputfields
		 */
		setKeyDownHandlerForField: function( fieldName ) {
			// Debug.log( "setKeyDownHandlerForField::" + fieldName );
			Search.getInputForFieldName( fieldName ).keydown( function( event ) {
				Search.Handlers._keyDown( event , fieldName );
			} );
		},

		/**
		 * Concrete keydown handler
		 * @param {object} event
		 * @param {string} fieldName
		 */
		_keyDown: function( event , fieldName ) {
			if( Search.state.suggestEnabled ) {
				if( Search.isKeyCodeForSuggest( event.keyCode ) ) {
					if( null == Search.state.suggestRequestRunning ) {
						this.suggest( event , fieldName );
					}
				} else {
					this.functionKeyAction( event , fieldName );
				}
			}
		},

		/**
		 * Dispatch functionKey hits
		 * @param Event event
		 * @param String fieldName
		 */
		functionKeyAction: function( event , fieldName ) {
			if( event.keyCode == Search.KEYCODE.bottom || event.keyCode == Search.KEYCODE.top ) {
				if( Search.state.suggestResponseFieldOpened != null ) {
					this._highlightSuggestItem( event );
				}
			} else if( event.keyCode == Search.KEYCODE.enter ) {
				this._enterKeyInSuggest( event , fieldName );
			} else if( event.keyCode == Search.KEYCODE.tab ) {
				this._tabKeyInSuggest( event , fieldName );
			}
		},

		/**
		 * Called when tab key is hit when suggest is opened
		 * @param {object} event the original event object passed
		 * @param {string} fieldName
		 */
		_tabKeyInSuggest: function( event , fieldName ) {
			Debug.log( "_tabKeyInSuggest " + fieldName );
//			Debug.log( event );
			Debug.log( "_tabKeyInSuggest::index" + Search.state.currentHighlightedElement.index );
//			Debug.log( "_tabKeyInSuggest::fieldName " + fieldName );
			Debug.log( "_tabKeyInSuggest::Search.state.currentHighlightedElement.fieldName " + Search.state.currentHighlightedElement.fieldName );
//			Debug.log( "_tabKeyInSuggest:: " + Search.state.currentHighlightedElement.fieldName.indexOf( fieldName ) != -1);

			if( Search.state.currentHighlightedElement.index > -1 &&
				Search.state.suggestResponseFieldOpened.indexOf( fieldName ) != -1 ) {

				var selection = Search.getSuggestULElementForFieldName( Search.state.suggestResponseFieldOpened ).children( 'li' ).get( Search.state.currentHighlightedElement.index );
				var value = $( selection ).children().html();
				Search.setItem( fieldName , value );
				Search.state.preventFormSubmit = false;
				Search.Handlers._closeSuggestAfterSelect( Search.state.suggestResponseFieldOpened );
			}
		},

		/**
		 * If Enter is hit in a focus of a form field,
		 * this method checks suggest-state.
		 * @param Event event
		 * @String fieldName
		 */
		_enterKeyInSuggest: function ( event , fieldName ) {
			if( Search.state.suggestEnabled && null != Search.state.suggestResponseFieldOpened ) {
//				 Debug.log( "_enterKeyInSuggest::Search.state.suggestResponseFieldOpened " + Search.state.suggestResponseFieldOpened );
//				 Debug.log( "_enterKeyInSuggest::fieldName " + fieldName );
//				 Debug.log( "_enterKeyInSuggest::index " +  Search.state.currentHighlightedElement.index );
//				 Debug.log( "_enterKeyInSuggest::currentHighlightedElement.fieldName " +  Search.state.currentHighlightedElement.fieldName );

				if( Search.state.suggestResponseFieldOpened.indexOf( fieldName ) != -1 &&
					Search.state.currentHighlightedElement.index > -1 ) {

					var selection = Search.getSuggestULElementForFieldName( Search.state.suggestResponseFieldOpened ).children( 'li' ).get( Search.state.currentHighlightedElement.index );
					var value = $( selection ).children().html();
					var fieldNameForInput = fieldName == 'where_advert' ? 'where' : fieldName;
					Search.setItem( fieldNameForInput , value );
					var openedResponseField = Search.state.suggestResponseFieldOpened;
					Search.closeSuggestFieldByFieldName( Search.state.suggestResponseFieldOpened );
					Search.Handlers._resetSuggestField( openedResponseField );

					// An exception is this: a suggest select in
					// where sends form if what is filled
					if( fieldNameForInput == 'where' &&
						Search.getInputForFieldName( fieldNameForInput ).val() != ""  &&
						Search.getInputForFieldName( 'what' ).val() != "" ) {

						Search.state.preventFormSubmit = false;
						Debug.log("_enterKeyInSuggest set preventFormSubmit to false");
					} else {
						Search.state.preventFormSubmit = true;
						Debug.log("_enterKeyInSuggest set preventFormSubmit to true");
					}

				} else {
					Debug.log("_enterKeyInSuggest set preventFormSubmit to false");
					Search.state.preventFormSubmit = false;
				}

				if( !Search.state.preventFormSubmit && navigator.appName.toLowerCase().indexOf( 'microsoft internet explorer') != -1 ) {
					//document.forms[0].submit();
					executeSubmit();
				}
			}
		},

		/**
		 * This Mehtod builds and starts the suggest-request.
		 * after that, the callback-method "Search.Handlers.processSuggest"
		 * will be called which builds the Outputfield and fills it with data.
		 * The concrete request, wrapped in Search.Handlers._suggestRequest is
		 * put into a timeout, because all field value data is not sent correclty
		 * @param Event event the original event object which starts the suggest
		 * @param String fieldName the fieldName in which the event has been started
		 */
		suggest: function( event , fieldName ) {
			// set global state that tells a request is currently running
			Search.state.suggestRequestRunning = fieldName;
			var url = Search.getRequestUrlForFieldName( fieldName );
			var properties = { search: fieldName };
			if( fieldName == "where" || fieldName == "where_advert" ) {
				properties.opposite = Search.getInputForFieldName( "what" ).val();
			}
			Search.state.delayedSuggestTimeout = window.setTimeout( function() {
				// Debug.log("Search.Handlers.suggest uses '" + Search.getInputForFieldName( fieldName ).val() + "' for field " + fieldName );
				properties.tag = Search.getInputForFieldName( fieldName ).val();
				Search.Handlers._suggestRequest( url , properties , Search.Handlers.processSuggest );
			} , Search.suggestDelay );
		},

		/**
		 * This is a wrapper for the direct XHR
		 * @param String url the reqwuest url
		 * @param Object properties an object with data to send to the server
		 * @param Function callback the callback funtion to process the response
		 */
		_suggestRequest: function( url , properties , callback ) {
			jQuery.getJSON( url , properties , callback );
		},

		/**
		 * This is the callback-method which is called by Search.Handlers.suggest-
		 * method. Its a xhr / jQuery.getJSON-callback
		 * @param Object data the result as javascript-object
		 * @param String textStatus the ajax status text.
		 */
		processSuggest: function( data , textStatus ) {
			var fieldName = Search.state.suggestRequestRunning;
			// Debug.log( fieldName );
			Search.state.suggestRequestRunning = null; // request is done here.
			if( textStatus == "success" ) {
				if( data != null && data.length > 0 ) {
					if( data[data.length-1].advertId !== undefined ) {
						fieldName = 'where_advert';
						Search.Handlers._setAdvert( data[data.length-1] );
						data.pop();
					}
					Search.Handlers._setData( data , fieldName );
					Search.closeAllSuggestFields( fieldName );
					Search.openSuggstFieldByFieldName( fieldName );
				}
				// Debug.log( data );
				// Debug.log( textStatus );
			} else {
				// Debug.log( "Error: Search.Handlers.processSuggest::textStatus: " + textStatus );
			}
		},

		/**
		 * This function is called by the method that processes the
		 * callback-data of a suggest request, if there are advert-data as
		 * last dataset in the server-result, it will be given to this method
		 * and set to its DOM
		 * @param {object} advertData
		 */
		_setAdvert: function( advertData ) {
			var properties = new Array('pretitle','title','subtitle','industry','address','city','detaillink');
			for( var property = 0; property < properties.length; property++ ) {
				if( advertData[properties[property]] !== undefined ) {
					$( '.suggest-advertisment .adv-' + properties[property]).css('display','block');
					$( '.suggest-advertisment .adv-' + properties[property]).html( advertData[properties[property]] );
				} else {
					if( properties[property] !== 'pretitle' ) {
						$( '.suggest-advertisment .adv-' + properties[property]).css('display','none');
						$( '.suggest-advertisment .adv-' + properties[property]).html( '<!-- -->' );
					} else {
						$( '.suggest-advertisment .adv-' + properties[property]).html( '&nbsp;' );
					}
				}
			}
		},

		/**
		 * Sets the suggest result items into the html-list
		 * @param Obejct data
		 * @param String fieldName
		 */
		_setData: function( data , fieldName ) {
			// Debug.log( "Search.Handlers._setData" );
			// Debug.log( data );
		    var html = new Array();
		    var even_odd = new Array("even","odd");
		    Search.Handlers._resetSuggestField( fieldName );
		    for( var i = 0; i < data.length; i++ ){
		    	var item = Search.suggestEntryTemplate;
		    	item = item.replace( /%%class%%/ , even_odd[i%2] );
		    	item = item.replace( /%%fieldName%%/ , fieldName );
		    	item = item.replace( /%%id%%/ , i );
		    	item = item.replace( /%%text%%/ , data[i] );
		        html.push( item );
		    }
		    Search.getSuggestULElementForFieldName( fieldName ).html( html.join( "" ) );
		    Search.Handlers.setSuggestFieldHandlers();
		    // Debug.log( Search.getSuggestULElementForFieldName( fieldName ) );
		},

		/**
		 * Empties the suggest result and resets the index of
		 * the current highlighted elemenr
		 * @param String fieldName
		 */
		_resetSuggestField: function( fieldName ) {
			Debug.log( "_resetSuggestField::fieldName: " + fieldName );
			// Debug.log( Search.getSuggestULElementForFieldName( fieldName ) );
			if( fieldName != null ) {
				Search.getSuggestULElementForFieldName( fieldName ).empty();
			} else {
				Debug.log( "ERROR in _resetSuggestField. given param fieldName is null" );
			}

			Search.state.currentHighlightedElement.index = -1;
		},

		/**
		 * There are several Mousehanders in the
		 * suggest output field, which is sometime removed
		 * from the DOM, so we use jQuery live and die
		 */
		setSuggestFieldHandlers: function() {
			var listElementsAnchor = $( '.suggest ul > li');
			Debug.log( "setSuggestFieldHandlers" );
			listElementsAnchor.click( Search.Handlers.selectSuggestItemByClick );
			listElementsAnchor.mouseover( Search.Handlers._mouseoverSuggestItem );
			listElementsAnchor.mouseout( Search.Handlers._mouseoverSuggestItem );
		},

		/**
		 * This is the concrete selection handler method
		 * which can be called by several handlers like
		 * click or some key handlers
		 * @param Event event the original event
		 */
		selectSuggestItemByClick: function( event ) {
			if( Search.state.suggestEnabled ) {
				var fieldName = event.target.parentNode.id.split( '_tag_' )[0];
				fieldName = fieldName.split( 'suggest_' )[1];

				Debug.log( "selectSuggestItemByClick::" + fieldName );
				// Debug.log( event.target );
				var value = $( event.target ).html();
				var fieldNameSuggest = fieldName;
				fieldName = fieldName == 'where_advert' ? 'where' : fieldName;
				Search.setItem( fieldName , value );

				// An exception is this: a suggest select in
				// where sends form if what is filled
				if( fieldName == 'where' &&
					Search.getInputForFieldName( fieldName ).val() != ""  &&
					Search.getInputForFieldName( 'what' ).val() != "" ) {

					Search.state.preventFormSubmit = false;
					Debug.log("_enterKeyInSuggest set preventFormSubmit to false");
					//document.forms[0].submit();
					executeSubmit();
				} else {
					Search.state.preventFormSubmit = true;
					Debug.log("_enterKeyInSuggest set preventFormSubmit to true");
				}
				Search.Handlers._closeSuggestAfterSelect( fieldNameSuggest );
			}
		},

		/**
		 * This method is called, if on focused inpout field
		 * cursor up or down ley is pressed.
		 * the Highlighting will be set to the first element if none
		 * is highlighted, or next or prev of curretn highlight.
		 * @paren Event event
		 */
		_highlightSuggestItem: function( event ) {
			var fieldName = event.target.id.split( '_search' )[0];
			var countOfItems = Search.getSuggestULElementForFieldName( Search.state.suggestResponseFieldOpened ).children().size();
			var currentIndex = Search.state.currentHighlightedElement.index;
			// Debug.log( "_highlightSuggestItem::countOfItems:" + countOfItems );
			// Debug.log( "_highlightSuggestItem::currentIndex:" + currentIndex );
			if( currentIndex > -1 ) {
				$( Search.getSuggestULElementForFieldName( Search.state.suggestResponseFieldOpened ).children().get( currentIndex ) ).removeClass( 'hover' );
			}

			if( event.keyCode == Search.KEYCODE.bottom ) {
				if( currentIndex < countOfItems-1 ) {
					currentIndex++;
				} else {
					currentIndex = 0;
				}
			} else if( event.keyCode == Search.KEYCODE.top ) {
				if( currentIndex > 0 ) {
					currentIndex--;
				} else {
					currentIndex = countOfItems-1;
				}
			}
			Search.state.currentHighlightedElement.index = currentIndex;
			Search.state.currentHighlightedElement.fieldName = fieldName;
			$( Search.getSuggestULElementForFieldName( Search.state.suggestResponseFieldOpened ).children().get( currentIndex ) ).addClass( 'hover' );
		},

		/**
		 * This is the mouseover and mouseout event
		 * which just de/highlights an entry
		 * @paran Event the original event object passed
		 */
		_mouseoverSuggestItem: function( event ) {
			var element = event.target;
			if( element.nodeName == 'A' ) {
				element = element.parentNode;
			}
			Debug.log( element.nodeName );
			if( event.type == 'mouseover' ) {
				$( element ).addClass( 'hover' );
				var index = element.id.split('_tag_')[1];
				Search.state.currentHighlightedElement.fieldName = Search.state.suggestResponseFieldOpened;
				Search.state.currentHighlightedElement.index = index;
			} else if( event.type == 'mouseout' ) {
				$( element ).removeClass( 'hover' );
				Search.state.currentHighlightedElement.fieldName = null;
				Search.state.currentHighlightedElement.index = -1;
			}
		},

		/**
		 * This is the concrete blurhandler which has to be
		 * set on the input fields
		 * @param Event event the passed original event object
		 */
		_blurInputFieldHandler: function( event ) {
			var fieldName = event.target.id.split( '_search' )[0];
			// Debug.log( Search.state.suggestResponseFieldOpened );
			/*if( Search.state.currentHighlightedElement.index == -1 ) {
				Search.Handlers._closeSuggestAfterSelect( fieldName );
			}*/
		},


		_closeSuggestAfterSelect: function( fieldName ) {
			if( Search.state.suggestResponseFieldOpened !== null &&
				Search.state.suggestResponseFieldOpened.indexOf( fieldName ) != -1 ) {

				Debug.log( "_closeSuggestAfterSelect" );
				var openedResponseField = Search.state.suggestResponseFieldOpened;
				Search.closeSuggestFieldByFieldName( Search.state.suggestResponseFieldOpened );
				// Debug.log( "_blurInputFieldHandler:: Search.state.suggestResponseFieldOpened=" + openedResponseField );
				Search.getSuggestULElementForFieldName( openedResponseField ).children( 'li' ).removeClass( 'hover' );
				// Debug.log( "_blurInputFieldHandler::li elements:"  + Search.getSuggestULElementForFieldName( openedResponseField ).children( 'li' ).removeClass( 'hover' ));
				Search.state.currentHighlightedElement.index = -1;
				Search.state.currentHighlightedElement.fieldName = null;
			}
		},

		/**
		 * This is the concrete focushandler which has to be
		 * set on the input fields
		 * @param Event event the passed original event object
		 */
		_focusHandler: function( event ) {
			if( Search.state.suggestEnabled ) {
				Search.state.preventFormSubmit = false;
				var fieldName = event.target.id.split( '_search' )[0];
				Search.closeAllSuggestFields( fieldName );
				if( event.target.value != "" ) {
					// Debug.log( Search.getSuggestULElementForFieldName( fieldName ).children().size() > 0 );
					if( fieldName == 'where' &&
						Search.getSuggestULElementForFieldName( fieldName+'_advert' ).children().size() > 0 ) {

						fieldName = fieldName+'_advert';
					}
					if( Search.getSuggestULElementForFieldName( fieldName ).children().size() > 0 ) {
						Search.openSuggstFieldByFieldName( fieldName );
					}
				}
			}
		},

		end: 0 // End Search.Handlers
	},

	/**
	 * Setting given Value to given input field,
	 * used in all places which puts suggest items to fields
	 * @param {string} fieldName fieldName of the form input
	 * @param {string} value the value to be set
	 */
	setItem: function( fieldName , value ) {
		fieldName = fieldName == 'where_advert' ? 'where' : fieldName;
		Search.getInputForFieldName( fieldName ).val( value );
		if( $('#suggest_choosed_' + fieldName ).size() == 1 ) {
			$('#suggest_choosed_' + fieldName ).val( value );
		}
	},

	/**
	 * Opens a suggest output field by given name
	 * @param String fieldName
	 */
	openSuggstFieldByFieldName: function( fieldName ) {
		if( Search.state.suggestEnabled ) {
			var field = Search.getSuggestFieldForFieldName( fieldName );
			if( field.css( 'display' ) == 'none' ) {
				field.show();
				Search.state.suggestResponseFieldOpened = fieldName;
			}
		}
	},

	/**
	 * Closes a suggest output field by given name
	 * @param String fieldName
	 */
	closeSuggestFieldByFieldName: function( fieldName ) {
		var field = Search.getSuggestFieldForFieldName( fieldName );
		if( field.css( 'display' ) != 'none' ) {
			field.hide();
			Search.state.suggestResponseFieldOpened = null;
		}
	},

	/**
	 * With this method we can close all suggest fields with one call.
	 * Additionally the old, global "closeAllLayers" method will be called,
	 * so all opened layers will be closed if defiend.
	 * Opiionally an exception can be given in order to hold one layer opened.
	 * @param String exceptFor
	 */
	closeAllSuggestFields: function( exceptFor ) {
		exceptFor = exceptFor !== undefined ? exceptFor : null;
		closeAllLayers( exceptFor );
		for( var i = 0; i < Search.fieldNames.length; i++ ) {
			if( Search.fieldNames[i] != exceptFor ) {
				Search.closeSuggestFieldByFieldName( Search.fieldNames[i] );
			}
		}
	},

	/**
	 * Get input field by given name
	 * @param String fieldName what|where
	 * @return jQueryDomElement
	 */
	getInputForFieldName: function( fieldName ) {
		var input = null;
		if( fieldName == 'where' ||  fieldName == 'what' ) {
			input = $( '#' + fieldName + '_search' );
		}
		return input;
	},

	/**
	 * Get error labal field for given fieldName
	 * @param String fieldName what|where
	 * @return jQueryDomElement
	 */
	getErrorLabelForFieldName: function( fieldName ) {
		var label = null;
		if( fieldName == 'where' ||  fieldName == 'what' ) {
			label = $('#' + fieldName + '_search_inner div.headersearch_error_line');
		}
		return label;
	},

	/**
	 * Get suggest output field by given fieldName
	 * @param String fieldName what|where|where_advert
	 * @return jQueryDomElement
	 */
	getSuggestFieldForFieldName: function( fieldName ) {
		var suggestField = null;
		if( fieldName == "what" || fieldName == "where" || fieldName == "where_advert" ) {
			suggestField = $( '#suggest_' + fieldName );
		}
		return suggestField;
	},

	/**
	 * Get the UL element of an output suggest field
	 * by given fieldName
	 * @param String fieldName
	 * @return jQueryDomElement
	 */
	getSuggestULElementForFieldName: function( fieldName ) {
		var suggestFieldList = null;
		if( fieldName == "what" || fieldName == "where" || fieldName == "where_advert" ) {
			suggestFieldList = $( '#suggest_' + fieldName + ' ul'  );
		}
		return suggestFieldList;
	},

	/**
	 * Get the Url for the XHR for given fieldName
	 * @param String fieldName
	 * @return String
	 */
	getRequestUrlForFieldName: function( fieldName ) {
		var requestUrl = null;
		if( fieldName == "what" ) {
			requestUrl = PATH_TO_SUGGEST_WAS;
		} else if( fieldName == "where" || fiedlName == "where_advert" ) {
			requestUrl = PATH_TO_SUGGEST_WO;
		}
		return requestUrl;
	},

	/**
	 * Check if input keyCode is a clphanum sign
	 * To be used eg to check if input is suggest-initiating input
	 * See http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
	 * @param int keyCode
	 * @return boolean
	 */
	isKeyCodeForSuggest: function( keyCode ) {
		var keyCodeForSuggest = true;
		jQuery.each( Search.KEYCODE , function( keyName , kCode ) {
			if( kCode == keyCode ) {
				keyCodeForSuggest = false;
			}
		} );
		// Debug.log( "isAlphaNum::isAlphaNum "  + keyCode + " " + keyCodeForSuggest );
		return keyCodeForSuggest;
	},

	/**
	 * Get the current selected (hovered) item in suggest output
	 * by given fieldName
	 * @param String fieldName
	 */
	getCurrentSuggestItemSelectionByFieldName: function( fieldName ) {
		// Debug.log( "getCurrentSuggestItemSelectionByFieldName:: " );
		return this.getSuggestULElementForFieldName( fieldName ).children( 'li.hover' );
	},

	/**
	 * enables suggest and removes
	 * autocompletition attributes on inputs
	 */
	enable: function() {
		if( false == Search.state.suggestEnabled ) {
			Search.state.suggestEnabled = true;
			Search.getInputForFieldName( 'what' ).removeAttr( "autocomplete" );
			Search.getInputForFieldName( 'where' ).removeAttr( "autocomplete" );
		}
	},

	/**
	 * disables suggest and resets
	 * autocompletition attributes on inputs
	 */
	disable: function() {
		if( true == Search.state.suggestEnabled ) {
			Search.state.suggestEnabled = false;
			Search.getInputForFieldName( 'what' ).attr( "autocomplete" , "on" );
			Search.getInputForFieldName( 'where' ).attr( "autocomplete" , "on" );
		}
	},

	end: 0 // End Search
};


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


$( document ).ready( function() {
// TODO Parameter der Search init übergeben, diese Condition soll nur die Suggest Funktion bestimen, nicht die der ganzen Suche
	if( ge('what_search') !== null &&
		( $('body').attr('id') !== undefined && $('body').attr('id').indexOf('product') ==-1 ) &&
		( $('body').attr('id') !== undefined && $('body').attr('id').indexOf('privat') ==-1 ) &&
		bodyClass.indexOf('produktsuche') == -1 &&
		bodyClass.indexOf('privat') == -1 &&
		$('#map_search').size() < 1 ) {

		Search.init();
	}
} );

/* End Search and Suggest */function killAllTooltipSemaphores(){
    window.clearTimeout(semaTimeoutTooltip);
    window.clearTimeout(semaTimeoutImgTooltip);
    window.clearTimeout(semaTooltip);
}


/**
 * 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;
		//Wallpaper zerhaut die Positionierung. Unschön aber geht nicht anders als das im Falle des Wallpapers 190px nach oben zu ziehen
		if($("#wallpaper_ads_01").length > 0) {
			topPos = topPos - 109;
		}
		$(_this.destinationSelector)
			.css("top",topPos + "px")
			.css("left",leftPos + "px");
	};
	this.init();
};
// End CLASS TooltipDynHeigh

// 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 = urlPrefix+'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(openFilter==="" || typeof(openFilter) == "undefined"){
         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(){
    return 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 = "";
	}
	return false;
}

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){
    if($('#finder').length > 0)
		hideBranchenfinder();

     if(openFilter==="" || typeof(openFilter) == "undefined"){
      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-22;
			if(($("#finder").length + $("#wallpaper_ads_01").length) > 1) {
				top = top - 109;
			}
            var left = coords.x +8;
            if($.browser.opera || $.browser.msie)
                      top =  top-0;
            $('#tooltip_info').css({"top":top+"px","left":left+"px"}).bgiframe().show();
        }
    }
}
// only used within Meine Gelbe Seiten
function showAnotherTooltip(element) {
	hideBranchenfinder();
    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 = absLeft(dies)-380;
    var y_pos = absTop(dies);
    var suffix = "_big_"+index ;
    var src = "";
    var url ="";
    currentWebToolTipIndex = index;
    closeAllLayers('tooltip_img_big_'+index);
    currentWebToolTip = 'tooltip_img_big_'+index;
    hideTooltipImg(currentTooltip);
      if(x_pos<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 = absLeft(element)+250;
    var y_pos = absTop(element);
    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="'+urlPrefix+'/static/img/icons/loading.gif" alt="loading" id="loading_gif" class="db" style="margin-top:45px" /></center>';
        $(element).attr('title','').attr('alt','');
        if(x_pos<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);
    }
}