//
// $Id: all.js,v 1.243 2009-10-16 09:44:50 drose Exp $
// 

var geocoder = null;
var nc = jQuery.noConflict(); 
var hashHistory = '';
var hashClickBlock = false;
var hashMapTimer = null;
var currentFocus = null;

var siteSettings = {
   ajaxSuspend : false  
};

function isIE() {
   return (navigator.appName.indexOf("Microsoft")!=-1); 
}

/**
 * retrieve cookie information
 * 
 * @param (string) Name - name of the cookie value to look into 
 * @return (string) - cookie value
 */
function get_cookie(Name) {
   
   var search = Name + "=";
   var returnvalue = "";
   
   if (document.cookie.length > 0) {
      
      offset = document.cookie.indexOf(search);
      
      // if the cookie exists
      if (offset != -1) {
         
         offset += search.length;
         // set the index of beginning value
         end = document.cookie.indexOf(";", offset); 
         
         // set the index of the end of cookie value
         if (end == -1) { 
            end = document.cookie.length;
         }
         returnvalue = unescape(document.cookie.substring(offset, end));
         
         
      }
      
   }
   
   return returnvalue;

}

/**
 * Manages Popunder Functionality for search results
 *
 * @param (bool) wait -    whether to delay popunder creation or not, 
 *                      use 2.5 sec delay if set to true   
 * @param (bool) update -  whether to force popunder creation. 
 *                      defaults to false, if set to true popunder will only
 *                      by updated, if its window already exists 
 *
**/
function popunder(wait, update) {
   
   /* disabled for now
   
   // popunder properties
   windowName = 'SearchUnder';
   windowUrl = '/dynamic/popunder';
   windowProperties = 'width=600, height=500,left=200,top=200,location=no,menubar=no,status=yes,toolbar=no';
   
   // requests triggered by search form must wait 
   if (wait) {
      windowUrl += '?wait=true';
   }
   
   // first time (neither is defined)
   if (!update && get_cookie('popunder') == '') {
      
      //  set cookie so to remember, popunder was / is active, reset close
      document.cookie = 'popunder=yes; path=/;';
      
   }
   
   // if update is specified, check if window is open / not closed
   if (get_cookie('popunder') == 'yes') {
      
      win = window.open(windowUrl, windowName, windowProperties);
      
      // NOTE: "hiding" does not work with firefox 3+ or opera 9.5+
      if (win) {
         win.blur();
         self.focus();
      }
      
   }
   // do nothing, user requested popunder to remain silent
   else {
      
   }
   
    */
   
   return false;
   
}

/**
 * handle second autocomplete form  
 * 
 * @param elt - dom object (should be an text-input field !)
 * @param context - optional: context || is not used right now
 * @return void
 */
function suggest_bind (elt, context) {
   
   nc("#sidebar-right-searchform input[name='PLZ']").remove();
   
   // select input field
   elt.select();
   
   // bind actions 
   if (elt && nc('.ac_results').length <= 1) {
      was = nc('#sidebar-right-searchform input[@name=WAS]').val();
      nc(elt).autocomplete('/wohnen/suggest_search.php', {
           minChars: 1,
           delay: 40, // 250 for online is recommended
           cacheLength: 0, // caching last 10 requests
           matchCase: false,
           mustMatch: false,
           autoFill: false, 
           selectFirst: true,
           max: 10,
           // moreItems: '<span>mehr ergebnissse</span>', 
           scrollHeight: 480,
           extraParams: {WAS: was, more: false, context: context}, 
           width: 200,
           // width: parseInt(nc(elt).css('width')) + 10, // input-width + 10px
           
           /**
            * format a result item 
            * 
            *  @param (int) row - part of returned data
            *  @param (int) position - position of result (starts with 1)
            *  @param (int) total - total number of returned results
            *  @param (string) term - search term used
            *  
            *  @return (string) formatted resultview  
           */
           formatItem: function (row, position, total, term) {
                         
             if (term.match(/^\d{5}$/)) {
               /* 
               // unfortunate to do on each call ...
               if (!nc('.ac_results').is('.sidebar_plz')) {
                  nc('.ac_results').addClass('sidebar_plz');
               }
               */
               return '<span class="a2name">' + row[1] + '</span>' + row[0]; 
                     
             }
             
             return row[0];
            
           }, 
           /**
            * format the result to be inserted into the input field
            * 
            *  @param (int) row - part of returned data
            *  @param (int) position - position of result (starts with 1)
            *  @param (int) total - total number of returned results
            *  
            *  @return (string) formatted resultview
           */
           formatResult: function (row, position, total) {
             
             return row[0];
             
           },
           /**
            * format a currently selected item
            * 
            * @param (string) value - content of item 
            * @param (string) term - search term
            * 
            * @return (string) formatted resultview
            */
           highlight: function(value, term) {
             
             return value;
             
           }
             
      });
      
      // 
      /**
       * update other form fields
       * 
       * @param (object) event - event of type result
       * @param (object) data - data the user selected
       * @param (string) formatted - string as formatted by fn formatResult
       * 
       */
      nc(elt).result( function(event, data, formatted) {
         
         var value = (data[0].match(/^\d{5}$/)) ? data[2] : data[1];
         nc('#detail-ort input[name=IDL]').val(value);
         
         if (is_search()) {
            document.BOXFORM.submit();
         }
         else {
            change_send_button();
         }
         
      });
   
   }
}

/**
 * place loading animation element onto screen
 * 
 * @param elt - above which element to put loading animation atop
 * @return
 */
function place_loader (elt, additional_class) {
   if (elt=='#spalte2' && !nc('#spalte2').length) elt = '#lspalte2';
   if (nc(elt)){
      e = nc(elt);
      pos = e.offset();
      l = nc('#loader');
      
      l.css({
        display: 'block',
        top: pos.top + 'px',
        left: pos.left + 'px',
        width: e.outerWidth() + 'px',
        height: e.outerHeight() + 'px'
      });
      
      // set special class  
      if (additional_class) {
         l.addClass(additional_class);
      }
      else {
         // previous class attributes 
         l.removeAttr('class');
      }
   }
}

/**
 * calculates needed height of seoheadline and applies minimum 
 * needed padding to search list container
 * @return void
 */
function mittelspaltenposition() {
   
   nc("#Main .Spalte-Mitte").css({
      paddingBottom: (nc("#search-immoguide-teaser").height() + 15) + 'px'
   });
}


/**
 * pan google map to given coordinate
 * 
 * @param lat latitude
 * @param long longitude
 * @param zoom zoomlevel
 * @return void
 */
function panMapIframe(lat,long, zoom) {
   
   mapframe = helper_get_mapframe();
   map = mapframe.map;
   evt = mapframe.GEvent;
   
   if (typeof map == 'object' && typeof evt == 'object') {
      
      // clear move event timer on map 
      evt.clearListeners(map, 'moveend');
      
      // determine zoom level to apply to 
      zoom = zoom || map.getZoom() || 12;
      
      // move map to where is supposed to 
      // map.panTo(new mapframe.GLatLng(lat, long));
      map.setCenter(new mapframe.GLatLng(lat, long), zoom);
      
      // reinstante move event handler, 
      evt.addListener(map,"moveend", function() {
         mapframe.gmaploadedc++; 
         if(! mapframe.gmapzoom) {
            mapframe.setlongglat(map.getCenter()); 
         }
         mapframe.gmapzoom = false; 
      });
      
      return true;
      
   }
   
   return false;
   
}

/**
 * dummy function used to loop until google map has finally loaded
 * @return void
 */
function panMapLoop (lat, long, zoom) {
   
   mapframe = helper_get_mapframe();
   
   if (typeof mapframe.map == 'undefined' && ( typeof mapframe.map != 'object') || (mapframe.map == null) ) {
      
      var hashMapTimer = window.setTimeout('panMapLoop(' + lat + ', ' + long + ', ' + zoom +')', 500);
      return hashMapTimer;

   }
   else {
   
      if (hashMapTimer != null) {
         window.clearTimeout(hashMapTimer);
      }
      
      // actually position map, again set a timeout as *some* browsers take their time
      return panMapIframe(lat,long, zoom);
      
   }
   
}

/**
 * dummy function used to loop until google map has finally loaded
 * @return void
 */
function streetshowLoop (html) {
   
   mapframe = helper_get_mapframe();
   
   if (typeof mapframe.map == 'undefined' && ( typeof mapframe.map != 'object') || (mapframe.map == null) ) {
      
      var hashMapTimer = window.setTimeout('streetshowLoop("' + html +'")', 500);
      return hashMapTimer;

   }
   else {
   
      if (hashMapTimer != null) {
         window.clearTimeout(hashMapTimer);
      }
      
      if (!html || typeof html == 'undefined' || html.length == 0) {
         html = ' ';
      }
      
      // delete any previous indicator
      nc('#streetsearch-indicator').remove();
      
      // make indicator appear
      nc('.map_wrapper').append('<div id="streetsearch-indicator"><p>' + html + '</p></div>');
      
      nc('#streetsearch-indicator').css({
         position: 'absolute',
         display: 'none',
         backgroundImage: 'url(http://images.immobilo.de/bilder/d1/bubble_ne_75.gif)',
         backgroundRepeat: 'no-repeat',
         width: '124px',
         height: '80px',
            top: nc('.map_wrapper').offset().top + 75 + 'px',
         left: nc('.map_wrapper').offset().left + 140 + 'px',
         margin: 0,
         padding: 0,
         zIndex: 1000,
         overflow: 'hidden'
      });
      
      // show indicator
      nc("#streetsearch-indicator").show(500);
      
      // hide it after 5 seconds 
      timer = window.setTimeout('nc("#streetsearch-indicator").hide(500)', 7500);
      
      // optionally bind "click" event to hide, then clear timer
      
   }
   
   
}

/**
 * show a hint on the map
 * @return void
 */
function showHintMap (html) {
   
   mapframe = helper_get_mapframe();
   
   if (typeof mapframe.map == 'undefined' && ( typeof mapframe.map != 'object') || (mapframe.map == null) ) {
      
      var hashMapTimer = window.setTimeout('showHintMap("' + html +'")', 500);
      return hashMapTimer;

   }
   else {
   
      if (hashMapTimer != null) {
         window.clearTimeout(hashMapTimer);
      }
      
      if (!html || typeof html == 'undefined' || html.length == 0) {
         html = ' ';
      }
      
      // delete any previous indicator
      nc('#map-hint').remove();
      
      // make indicator appear
      nc('.map_wrapper').append('<div id="map-hint"><p>' + html + '</p></div>');
      
      nc('#map-hint').css({
         position: 'absolute',
         display: 'none',
         backgroundImage: 'url(http://images.immobilo.de/bilder/d1/bubble_ne_75.gif)',
         backgroundRepeat: 'no-repeat',
         width: '124px',
         height: '80px',
         top: nc('.map_wrapper').offset().top + 195 + 'px',
         left: nc('.map_wrapper').offset().left + 20 + 'px',
         margin: 0,
         padding: 0,
         zIndex: 1000,
         overflow: 'hidden'
      });
      
      // show indicator
      nc("#map-hint").show(500);
      
      // hide it after 5 seconds 
      timer = window.setTimeout('nc("#map-hint").hide(500)', 7500);
      
      // optionally bind "click" event to hide, then clear timer
      
   }
   
   
}

/**
 * determine whether a given hash key is in hash or not
 * 
 * @param item string to match, partly or complete key-value pair
 * @param strict (optional) boolean whether only strict matches to be perform
 * @return boolean 
 */
function dynamic_bookmark_has (item, strict) {
   
   currentHash = (window.location.hash.length > 0) ? window.location.hash : '';
   
   if (currentHash.length > 0) {
      
      // must match complete key-value pair
      if (strict) {
         
         return (currentHash.indexOf(item)) ? true : false;
         
      }
      else {
         
         parts = item.split('_');
         if (currentHash.match(new RegExp('\/' + parts[0] + '_[aA0-zZ9]+'))) {
            return true;
         }
         
      }
      
   }
   
   return false;  
      
}

/**
 * sets, updates, or deletes an item from current window.location.hash
 * 
 * @param item string to look for, expects format 'string_string'
 * @param mode (optional) defaults to put, 
 *             'del' removes complete key-value pair
 * @return boolean always returns false
 */
function dynamic_bookmark_set (item, mode) {
   
   currentHash = (window.location.hash.length > 0) ? window.location.hash : '';
   parts = item.split('_');
   regEx = new RegExp('\/' + parts[0] + '_[aA0-zZ9]+');
   item = (item.indexOf('/') == -1) ? '/' + item : item;

   // default is to add
   if (!mode || mode == 'add') {
      
      if (currentHash.length == 0 || currentHash.indexOf(parts[0] + '_') == -1) {
         
         window.location.hash = currentHash + item;
      }
      else {
         window.location.hash = currentHash.replace(regEx, item);
      }

   }
   else if (mode == 'del' && (currentHash.indexOf(parts[0]) > -1) ) {
      window.location.hash = currentHash.replace(regEx, '');
   }

   return false;
}

/**
 * trigger refresh of a search list 
 * expects a well formed searchparameters hash 
 * 
 * @param (string) hash - hash to use
 * 
 * @return void
 */
function dynamic_bookmark_refresh (hash, do_check) {
	if (hash) {
      if (do_check) check_need_to_search(hash); // only check if hash-search needs to be executed on initial page display
      else execute_dynamic_bookmark_refresh(hash);
   } else {

      // if this is not the initial view ...
      if (hashHistory.length > 0) {

         if (hashClickBlock) {

                window.location.hash += hashHistory;
                hashClickBlock = false;
                
         }
         else {
            
            // update current hash in history
            hashHistory = '';
            
            // reload the page 
            place_loader('#Main');
            window.location.reload();
            
         }
         
      
      }
      
   }
   
}

/**
 * check if search needs to be executed
 */
function check_need_to_search(hash){
   var url = "/wohnen/hash_suche.php?CNTS=1";
   url = append_timestamp_to_ajax_url(url);
   
   nc.get(url, {}, function(data, textStatus) {
      if (textStatus == 'success'){
         if (data=='true') execute_dynamic_bookmark_refresh(hash);
      }
   }, 'text');
}
function execute_dynamic_bookmark_refresh (hash){
   //save postcode in BOXFORM
	var regexp = /Plz_([0-9]{5})/;
	var plz = hash.match(regexp);
	if(plz && plz.length>0) {
		document.BOXFORM.PLZ.value = plz[1];
	}
   // strip leading hash of hashHistory
   if (hashHistory.indexOf('#') === 0) {
      hashHistory = hashHistory.slice(1, hashHistory.length);
   }
   
   // do comparisons
   if (hash == 'open_emailalert') {
      
      nc(document).ready(function(){
         
         show_hide_ea_box('ealert_box1',0,'/wohnen/get_register.php?DO=emaila','ealert_box',1);
         hashHistory = window.location.hash;
      });
      
      return false;
      
   }
   else {
      
      if ((hashHistory == '') || (hash != hashHistory)) {
         
         /*
         dummy = hashHistory;
         mapInfo = false;
         
         // map settings - remove any of those keys as well 
         if (hash.index('Karte_') || dynamic_bookmark_has('Kartentyp_')) {
            
            // save hash without map infos 
            mapInfo = true;
            
         }
         */
         
         
         // update current hash in history
         hashHistory = hash;
         
         if (is_search()) {
            
            // only update if explicitly defined  
            if (siteSettings.ajaxSuspend == true) {
               
               // but do so only on first page impression
               siteSettings.ajaxSuspend = false;
               
            }
            else {
               // check if only map size / type have changed 
/*                
               if (mapInfo) {
                  
                  filters = new Array('Karte', 'Kartentyp');

                  for (e in filters) {
                      regExp = new RegExp('\/' + filters[e] + '_[aA0-zZ9]+');
                      hash = hash.replace(regExp, '');
                      dummy = dummy.replace(regExp, '');
                  }
                  
               }
               // do not reload if only map size / type have changed
               if (hash != dummy) {
*/                  
                  
                  var a = new Array(); 
                  if(document.BOXFORM) {
                     for(var i = 0 ; i < document.BOXFORM.elements.length; i++) {
                        e = document.BOXFORM.elements[i];
                        if (e.name=='WAS' || e.name=='TYP' || e.name=='WO' || e.name=='KEYWORDS'){
                           if(e.type == 'checkbox') {
                              if(e.checked) {
                                 a.push(e.name + '=' + encodeURI(e.value));
                              }
                           } else {
                              if (e.value != '') {
                                 a.push(e.name + '=' + encodeURI(e.value));      
                              }
                           }
                        }
                     }
                  }
                  formVars = a.join('&');
                  
                  // build params
                  var params = hash.replace(/_/g, '=').split('/');
                  var url = "/wohnen/hash_suche.php?"+encodeURI(params.join('&'));

                  if(formVars.length>0) url+="&"+formVars;
                  
                  // refresh page
                  if (nc('#Main').hasClass('extractedMap')) {
                     place_loader('#spalte2');
                  }
                  else {
                     place_loader('.layout_col_3');
                  }
                  
                  ajax_call(url);
/*                   
               }
*/                
            }
            
         }
         
      }
      else {
         
         // implicitly assume => (hash == hashHistory)
         
         return false;
         
      }

      
   }
}


/**
 * re-creates sliders in left sidebar form 
 * @param settings - slider min, max, and step settings
 * @return void
 */
function dynamic_bookmark_sliderrestore(settings) {
   
   rfinal = new Array();

   rfinal.push(
      {run: function(){
        add_sl_contoller("slider_PRIZE",settings.price.from,settings.price.to,"PFROM","PTO",settings.price.step);
      }},
      {run: function(){
        add_sl_contoller("slider_SIZE",settings.size.from,settings.size.to,"SFROM","STO",settings.size.step);
      }},
      {run: function(){
        add_sl_contoller("slider_ROOMS",1,7,"RFROM","RTO",0); // why step = 0 ?
      }},
      {run: function(){
        add_sl_contoller("slider_RADIUS",1,20,"RADIUS","");
      }}
   );

   nc(document).ready(function () {
	   run_final();
   });
}

function dynamic_bookmark_updatehash (key, val) {
      
   if (!isNaN(val)) {
      
      var h = window.location.hash;
      var hash = h;
      var i = null;
      var r = null;
         
      // strip leading hash of hashHistory
        if (h.indexOf('#') === 0) {
           h = h.slice(1, h.length);
        }
      
      i = h.indexOf(key);
      
        // either complete 
        if (i == -1) {
         hash += '/' + key + '_' + val;
        }
        // or replace
        else {
      
         var re = new RegExp(key + '_[0-9]+');
         hash = h.replace(re, key + '_' + val);
      
      }


      //HSF-480 if "Sort" changed, then go to page 1
      if(key=="Sort") {
        h = hash; 
        if (h.indexOf('#') === 0) {
           h = h.slice(1, h.length);
        }
        i = h.indexOf('Seite');
        // either complete 
        if (i == -1) {
          hash += '/Seite_0';
        }
        // or replace
        else {
           var re = new RegExp('Seite_[0-9]+');
           hash = h.replace(re, 'Seite_0');
        }
      }

      // inject updated hash
      window.location.hash = hash;
}
   
   return false;
   
}

/**
 * retrieve window object google maps is located in
 * 
 * uses src-property to find the correct iframe if name is changed / absent
 * 
 * @return window object, or false if no matching frame was found  
 */
function helper_get_mapframe () {

   if (typeof map_iframe === 'object') {
      return map_iframe;
   }
   else if (typeof parent.map_iframe === 'object') {
      // just return the iframe object
      return parent.map_iframe;
      
   }
   else if (typeof window.frames['map_iframe'] === 'object') {
      
      // just return the iframe object
      return window.frames['map_iframe'];
      
   }
   else {
      
      // iterate over list of frames ...
      i = window.frames.length;
      
      for (var j = 0; j < i; j++) {
         
         // ... and find the one with the "correct" url
         if (window.frames[j].location.href.match(/\/wohnen\/gliste\.php/)) {
            
            return window.frames[j]; 
            break;
            
         }
         
      }
      
   }

   return false;
   
}

function mapmarkers_reduce (max) {

   var t = 250; // timeout for map is not loaded yet loop 
   var w = window.frames['map_iframe']; // frame containing map 
   var m = w.map; // map object 
   
   // loop until p is defined
   if (!m || typeof m !== 'object' || !m.isLoaded()) {
      window.setTimeout('mapmarkers_reduce(' + max + ')',t);
      return false;
   }
   
   var p = w.markers; // markers array in map-iframe
   var l = p.length; // shortcut for counting markers in map-iframe
   var x = max || 30; // use either param 'max' or default to max of 30 pins
      
   if (typeof max !== 'undefined' && max === 0) {
      
      m.clearOverlays();
      
      // clear any markers array
      w.markers = [];
      gMapArray.ITEMS = [];
      pinlist.markers = [];
      pinlist.pins = [];
      pinlist.generation = 0;
      
      nc('#storage').empty();
      
      
   }
   else {
      
      while (l > 0 && l > x) {
         
         // remove markers
         /*
         del = p.shift();
         l = p.length;
         m.removeOverlay(del);
         */
         /*
         while (del = p.shift()) {
            // remove popups
            lat = del.getLatLng().lat();
            lng = del.getLatLng().lng();
            id = new String('#gmapoverl' + lat + '-' + lng).replace(/\./g, '');
            nc('#storage ' + id).remove();
         }
         */
         
      }
      
   }
      
}



function checktopform() {
  //var f = document.TOPFORM || document.topform_search || null;
  var f = document.FM || null;
  
  if (null != f) {
     
     var e = new Array(); 
     if(f.WAS.value == '' ) {
        e.push("Bitte 'Miete' oder 'Kaufen' w&auml;hlen");  
     } 
     // HSF-623
     if(f.WO.value == '' || f.WO.value == 'Neue Suche: Ort / PLZ') {
        e.push("Bitte einen Ort, eine PLZ oder Strasse eingeben"); 
     } 
     if (!isNaN(f.WO.value) && !f.WO.value.match(/^[0-9]{5}$/)) {
        e.push("Bitte eine Postleitzahl eingeben");
     }
     
     if(e.length > 0) {
        alert(e.join("\n")); 
        return false; 
     } else {
        // launch popunder
        popunder(true);
        return true; 
     } 
     
  }
  
} 

var frontpage = {
      
   mapclick: function(elt) {
   
      if (document.FM) {
         
         var idl = elt.attributes['id'].nodeValue.replace(/^frontpagemap-/, '').replace(/_/, ':');
         document.FM.WO.value = nc('strong', elt).text() || '-';
         document.FM.IDL.value = idl;
         
         // make sure to only submit numerical values
         var resetfields = ['PFROM', 'PTO', 'RFROM', 'RTO', 'SFROM', 'STO'];
         
         for (var i = 0; i < resetfields.length; i++) {
            if (isNaN(document.FM[resetfields[i]].value)) {
               document.FM[resetfields[i]].value = '';
            }
         }
         
         // HSF-681, only applies to clicks on map
         if (nc(elt).hasClass('hublink')) {
        	 urlparts = elt.attributes['href'].replace(/^\//, '').split('/');
        	 document.FM.WAS.value = (urlparts[0] === 'mieten') ? 'MIETE' : 'KAUF';
        	 switch (urlparts[1]) {
        	 case 'haus':
        		 document.FM.TYP.value = 'HAUS';
        		 break;
        	 case 'wohnung':
        		 document.FM.TYP.value = 'WOHNUNG';
        		 break;
        	 case 'gewerbe':
        		 document.FM.TYP.value = 'GEWERBE';
        		 break;
        	 }
         }

         document.FM.submit();
         
      }
   
      return false;
   
   }
      
};

var SERPS = {
		refreshPrimaryNav: function() {
			nc.get('/dynamic/refresh_primary-navigation', function(retval, msg) {
				if (msg === 'success') {
					var primaryLinks = eval(retval);
					nc('#MainNav a.primary-navigation-link').each(function(i) {
						nc(this).attr({title: primaryLinks[i].title, 'href': primaryLinks[i].href}).html(primaryLinks[i].content);
					});
				}
			});
		}
}

var EASTEREGGS = {

   tetris: {
   
      left:    750,
      bottom: 500,
      state:   'normal',
      outersize: {
         top: 55,
         bottom: 15,
         left: 10,
         right: 5
      },
      normal:  {
         html: '',
         title: 'Bilder',
         width: 0,
         height: 0
      },
      flash: {
         html: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' + 
            'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="400" height="443">' + 
            '<param name="movie" value="http://www.diggygames.com/swf/tetris.swf"> ' + 
            '<param name="quality" value="high"> ' +  
            '<embed src="http://www.diggygames.com/swf/tetris.swf" width=400 height=443 align="center" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed> ' +
            '</object>',
         title: 'Viel Spass !!!',
         width: 400,
         height: 445
      },
      init: function() {
         // only trigger this if at detail view
         if (location.pathname && location.pathname.match(/^\/immobilien\/(M|K){1}([0-9]+)$/)) {
            
            var bodyHeight = nc('#Main').height();
            var bodyWidth = nc('#Main').width();
            var that = this;
            
            this.normal.html = nc('#dhtmlWindow').find('.drag-contentarea').html();
            this.normal.width = nc('#dhtmlWindow').find('.drag-contentarea').width();
            this.normal.height = nc('#dhtmlWindow').find('.drag-contentarea').height();
            
            nc('#dhtmlWindow').bind('mousedown mouseup', function(e) {
               
               nc('#dhtmlWindow .drag-controls').bind('click', function(e) {
                  dhtmlwindow.close(document.getElementById('dhtmlWindow'));
               });
               
               var titletag = nc('.drag-handle').html();
               
               if ((nc(this).offset().top > (bodyHeight + EASTEREGGS.tetris.bottom)) || 
                     (nc(this).offset().left > (bodyWidth + EASTEREGGS.tetris.left)) ) {
                  
                  if (EASTEREGGS.tetris.state === 'normal') {
                     
                     EASTEREGGS.tetris.state = 'flash';
                                          
                     nc('#dhtmlWindow').css({
                        width: EASTEREGGS.tetris.flash.width + EASTEREGGS.tetris.outersize.left + EASTEREGGS.tetris.outersize.right + 'px',
                        height: EASTEREGGS.tetris.flash.height + EASTEREGGS.tetris.outersize.top + EASTEREGGS.tetris.outersize.bottom + 'px'
                     }).find('.drag-contentarea').html(EASTEREGGS.tetris.flash.html).css({
                        width: EASTEREGGS.tetris.flash.width + 'px',
                        height: EASTEREGGS.tetris.flash.height + 'px'
                     }).end()
                     .find('.drag-handle').html(titletag.replace(/^[aA-zZ\s!\.,\?\xe4\xc4\xd6\xf6\xdc\xfc\xdf]+/, EASTEREGGS.tetris.flash.title))
                     .find('.drag-controls').bind('click', function(e) {
                        
                        // re-center dialog if it was way outside normal page dimension  
                        if (EASTEREGGS.tetris.state === 'flash') {
                           
                           var container = nc('#dhtmlWindow');
                           var content = nc('#Main');
                           
                           var c_left = Math.max(Math.ceil(((content.width() - container.width()) / 2) + content.offset().left), 0);
                           var c_top = Math.max(Math.ceil(((content.height() - container.height()) / 2) + content.offset().top), 0);
                           
                           container.css({
                              left: c_left + 'px',
                              top: c_left + 'px'
                           });
                        
                        }
                     
                        dhtmlwindow.close(document.getElementById('dhtmlWindow'));
                        
                     }).end();
                     
                  }
                  
                  
               }
               else {
                  
                  if (EASTEREGGS.tetris.state === 'flash') {
                     
                     EASTEREGGS.tetris.state = 'normal';
                     
                     nc('#dhtmlWindow').css({
                        width: EASTEREGGS.tetris.normal.width + EASTEREGGS.tetris.outersize.left + EASTEREGGS.tetris.outersize.right + 'px',
                        height: EASTEREGGS.tetris.normal.height + EASTEREGGS.tetris.outersize.top + EASTEREGGS.tetris.outersize.bottom + 'px'
                     })
                     .find('.drag-contentarea').html(EASTEREGGS.tetris.normal.html).css({
                        width: EASTEREGGS.tetris.normal.width + 'px',
                        height: EASTEREGGS.tetris.normal.height + 'px'
                     }).end()
                     .find('.drag-handle').html(titletag.replace(/^[aA-zZ\s!\.,\?\xe4\xc4\xd6\xf6\xdc\xfc\xdf]+/, EASTEREGGS.tetris.normal.title))
                     .end();
                     
                  }
                  
               }
            
            });
            
         }
         
      }
      
   }
      
}

/** 
 * validator function for frontpage search form
 * 
 * @param (object) form - form element to validate against
 * @return bool - status of operation 
 */
function check_fm_form(form) {
   
   if (document.getElementById("STRS")) {
      
      // do not submit if streetsearch active but has no coordinates
      if (parseInt(document.getElementById("STRS").value)==1 && strsForced==false){
         if (parseInt(document.getElementById("LAT").value)==0 && parseInt(document.getElementById("LONG").value)==0){
            // do google request if not already visible
            //if(document.getElementById('search_suggest_rahmen').style.display == "none"){
            searchSuggest(2); 
            //}
            return false;
         }
      }
   }
   
   if (strsForced==true && parseInt(document.getElementById("LAT").value)==0 && parseInt(document.getElementById("LONG").value)==0){
   // set streetsearch to off, if it was forced before but couldn´t find anything
      document.FM.STRS.value=0;
      strsForced=false;
   }
   
   // fallback for deprecated use of validator ... 
   if (typeof form != 'object') {
      
      var submit = true;
      
      if (typeof document.FM == 'object') {
         switch (document.FM.WO.value){
         
            case "":    
               
               submit = false;
               document.FM.WO.focus();
               
               break;
                     
            case "Geben Sie Ihr Bundesland ein.":
            case "Geben Sie Ihre Stadt, PLZ oder Straße ein.":
            case 'Gib Deine Wunsch-Stadt oder PLZ an.':

               submit=false;
               
               document.FM.WO.value="";
               document.FM.WO.focus();
               document.FM.WO.select();
               
               break;
                     
         }
      }
   
      return submit;
      
   }
   else {
      
      errors = '';
      var field_descriptions = {PFROM: 'Preis von', PTO: 'Preis bis' };
      
      nc('input[type=text]', form).each(function() {
         
         formelement_name = nc(this).attr('name');
         
         // switch is available since js version 1.2
         switch (formelement_name) {
         
         case 'WO':
            
            if (this.value == '' || this.value == 'Geben Sie Ihr Bundesland ein.' || this.value == 'Geben Sie Ihre Stadt, PLZ oder Straße ein.' || this.value == 'Gib Deine Wunsch-Stadt oder PLZ an.') {
               
               if (this.value == 'Gib Deine Wunsch-Stadt oder PLZ an.') {
            	   errors += "Bitte trage einen Wunschort oder PLZ ein.";
               }
               else {
            	   errors += "Bitte geben Sie einen Ort an, in dem Sie nach Immobilien suchen wollen.\n";
               }
            
               
            }
            else if (!isNaN(this.value) && !this.value.match(/^[0-9]{5}$/)) {
               
               errors += "Bitte geben Sie eine Postleitzahl ein.\n";
               
            }
            
            break;
            
         default:
            
            if ((this.value == 'von' && formelement_name.substring(1, formelement_name.length) == 'FROM') || (this.value == 'bis' && formelement_name.substring(1, formelement_name.length) == 'TO')) {
            
               // reset value of input field
               this.value = '';
               
            }
            else if (this.value != '' && (isNaN(this.value) || this.value < 0)) {
               
               // apply indicator for "error" field 
               // this.style.border = '1px solid #996600';
               
               errors += "\nBitte tragen Sie im Feld »" + nc(this).attr('title') + "« eine positive ganze Zahl ein.";
            }
            
         break;
         
         }
         
      });
      
      // if fields did not validate, show all errors in ugly alert-box
      if (errors.length > 0) {
         
         // TODO: make this fancy
         errors = "Bitte überprüfen Sie Ihre Eingaben:\n\n" + errors;
         alert(errors);
         
      }
      else {
         // launch popunder
         popunder(true);
         return true;
      }
      
   }

   return false;

}

function flip(a) {
   if(document.getElementById(a)) {
      if(document.getElementById(a).style.display == 'none') {
         document.getElementById(a).style.display = 'block';
         if (document.getElementById(a+"_link")){
            document.getElementById(a+"_link").style.backgroundImage = "url(http://images.immobilo.de/bilder/minus.gif)";   
         }
      } else {
         document.getElementById(a).style.display = 'none';
         if (document.getElementById(a+"_link")){
            document.getElementById(a+"_link").style.backgroundImage = "url(http://images.immobilo.de/bilder/plus.gif)";
         }  
      }
   }
   return false; 
}

function set_radius_slider(radius){ /* sets the radius-slider to the position which is given by the map*/
   
   if (document.BOXFORM.RADIUS_user_search) {
      
      if (document.BOXFORM.RADIUS_user_search.value != 1) {
         
         document.BOXFORM.RADIUS_control.value = "false";
         document.BOXFORM.RADIUS_user_search.value = 0;
         nc("#slider_RADIUS").slider('moveTo',radius/100,0);
         document.BOXFORM.RADIUS.value=radius/1000;
         document.BOXFORM.RADIUS_control.value="true";

         
      }
   
   }

}


function setfelder(wo,was,treffer, formelements) {
   
   //var topform = document.TOPFORM || document.topform_search || null;
   var topform = document.FM || null;
   var boxform = document.BOXFORM || document.sidebar-right-searchform || null;
   
   if (null != topform) {
       
	   // HSF-623
	   if (topform.WO.value !== 'Neue Suche: Ort / PLZ') {
		   topform.WO.value = wo;
	   }
	   
      if (was == 'MIETE') {
         topform.WAS[0].selected = true;
      }
      else if (was == 'KAUF') {
         topform.WAS[1].selected = true;
      }
      
   }
   
   if (null != boxform) {
      
      if (boxform.WO.value == '-') {
         boxform.WO.value = wo;
      }
      
   }
   
   var wo2 = wo;
   
   if(document.getElementById('suche_typ_TXT')) {
       wo2 = document.getElementById('suche_typ_TXT').innerHTML + ' in ' + wo ; 
   }
   
   // alter formdata if told so 
   if (typeof formelements == 'object') {
      
      nc.each(formelements, function (key, value) {
         
         // assume we want to update innerHTML
         if (key.indexOf('#') === 0) {
            nc(key).html(value);
         }
               
      });
      
   }
   
   
}

function setImmoguideUrl(id) {
   
   if (document.getElementById('immoguidemenu')) {
      
      if (isNaN(id) && (id.indexOf('/stadt/') === 0)) {
         
         document.getElementById('immoguidemenu').href = id;
         
      }
      else {
         document.getElementById('immoguidemenu').href='/stadt/' + id; 
      }
      
   }
   
   if(document.getElementById('immogval')) {
      document.getElementById('immogval').value = id;
   }
} 

/** 
 * gets executed every time form data changes
 * 
 * @param w - a form element
 * @return void 
 */
function onch(w) {
   
	// HSF-687 redirect without clearing searchform
	if (w.value.match(/^\/(neubau|hausbau)\/(.+)/)) {
		self.location.href = w.value;
		return;
	}
	
   //  Begin for indextool
   makeindextool('Suche Sitebar','select','', index_data);
   // End for indextool
   
   // reset price sliders if rental / sale change occurs 
   if (w.name == 'WAS') { 
      document.BOXFORM.PFROM.value=''; 
      document.BOXFORM.PTO.value='';
   }

   // replace background image for "submit" button
   if (!is_search()) {
      
      change_send_button(); 
      return false;
      
   }
   else if ((w.name == 'TYP' || w.name == 'WAS')
         || (w.attributes['id'].nodeValue != 'sidebar-searchfield')) {
      
      // submit form
      document.BOXFORM.submit();
      
   }
    
}

function onch_hb(w){
   document.BOXFORM.submit();
}

/**
 * checks wether the radius-slider should start the onchange event 
 * (not true when the change comes from the map)
 * 
 * return void
 */
function absenden_check() {

   if (document.BOXFORM.RADIUS.value == nc("#slider_RADIUS").slider('value', 0) / 10) {
      
      if (document.BOXFORM.RADIUS_control.value != "false") {
         
         document.BOXFORM.RADIUS_user_search.value = 1;
         
         nc('a#reset-slider-img').addClass('active');

         absenden();
   
      }

   }
}

/** 
 * sets indextools-data and submits sidebar form
 * 
 * @return
 */
function absenden() {
   
   // if we're not at a search list view, just update bg-image for submit button
   if (!is_search()) {
      
      change_send_button();
      return false;
  
   }
   
   // indextools initialization
   if (document.BOXFORM.PFROM.value != index_data['preis_min'] || 
      document.BOXFORM.PTO.value != index_data['preis_max'] || 
      document.BOXFORM.SFROM.value != index_data['grosse_min'] || 
      document.BOXFORM.STO.value != index_data['grosse_max'] || 
      document.BOXFORM.RTO.value != index_data['zimmer_max'] || 
      document.BOXFORM.RFROM.value!=index_data['zimmer_min'] ) {
      
      // write indextools -> sidebar search
      makeindextool('Suche Sitebar','','',index_data);
      
   }
   else {
      
      // write indextools -> map movement
      makeindextool('Suche Karte','','',index_data);
      
   }
   
   // do ajax reload of search liste only if we're a search view
   if (is_search()) {
      
      if (document.BOXFORM.RADIUS_user_search.value == '1') {
         
         if (document.BOXFORM.LAT.value == '' || document.BOXFORM.LONG.value == '') {
            
            mapframe = helper_get_mapframe();
            
            if (mapframe.map) {
               
               centerpoint = mapframe.map.getCenter(); 
               lat = centerpoint.lat();
               lng = centerpoint.lng();
               
               document.BOXFORM.LAT.value = lat;
               document.BOXFORM.LONG.value = lng;
               
            }
            
            
         }
      }
      
      if (document.BOXFORM.LAT.value != '' && document.BOXFORM.LONG.value != '') {
     	 document.BOXFORM.PLZ.value = "";
      }
      
      ajax_reload();
      
   }
   
}



function boxform(wo,idl) {
   document.BOXFORM.WO.value = wo; 
   document.BOXFORM.IDL.value = idl; 
   document.BOXFORM.submit(); 
}

function boxformsend(wo,idl) {boxform(wo,idl)} 

/************************
  AJAX Suggest 
*************************/
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
   if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
   } else if(window.ActiveXObject) {
      return new ActiveXObject("Microsoft.XMLHTTP");
   } else {
	   alert('Your browser does not seem to support XMLHttpRequest.');
   }
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
var place_suggest = false; 


//Called from keyup on the search textbox.
//Starts the AJAX request.


function searchSuggest(mehr, context, event) {
   if (currentFocus!=null){
      currentFocus = null;
      place_suggest = true;
   }
   
   var Taste = -1;
   if(mehr != '1' && mehr != '2') {
     if(window.event) {
      evt = window.event; 
      Taste = evt.keyCode;
     } else {
      if(mehr) {
         Taste = mehr.which; 
      }
     }
//   document.getElementById("Ergebnis").innerHTML += " "+Taste;
     if(Taste == 40 ||  Taste == 38 || Taste == 13 ) {
      return;  
     }
     mehr = ''; 
   } 
   if (Taste==9 || Taste==16) return false; // do nothing if tab or shift
   
   // forcefully abort any ajax-call underway
   if (suggestActive) {
	  searchReq.abort(); 
	  suggestActive = false;
	  searchReq = new XMLHttpRequest();
   }
   // else {
   if (! suggestActive ) {
      if (searchReq.readyState == 4 || searchReq.readyState == 0) {
         if(context=='hbselectbtn'){
            var str = '';
         }else{
            // if (typeof event != 'undefined') {
        	 if (event && event.data && event.data.element) {
               var str = event.data.element.value;
            }
            else {
               var str = (document.getElementById('txtSearch').value);
            }
         }
         
         // HSF-324: allow string, or numbers from 1-5 digits
         if ((str.length > 0 && isNaN(str)) || (str.match(/^\d{1,5}$/)) || document.FM.WAS.value=='HAUSBAU') {
            
            suggestActive = true;
            
            // if (typeof event != 'undefined') {
            if (event && event.data) {
               var add = add_was_typ(event.data.element);
            }
            else {
               var add = add_was_typ(document.getElementById('txtSearch'));
            }
            // if (typeof event != 'undefined') {
            if (event && event.data) {
               context = event.data.context;
            }
            else {
               context = '';
            }
            
            if (context == '' && nc('body').hasClass('frontpage')) {
               context = 'front'; 
            }
            scrpt='suggest_search';
            if (document.getElementById("STRS")) {
               if (parseInt(document.getElementById("STRS").value)==1){
                  scrpt='suggest_gsearch';
                  str = escape(str);
                  suggestActive=false;
                  if (Taste != -1) return;
                  
                  if (document.getElementById("sucheText")){
                     div = document.getElementById("sucheText");
                     div2 = document.createElement('div');
                     div2.id = "loadingdiv";
                     div2.style.position = "absolute";
                     div2.style.top = "8px";
                     div2.style.left = "389px";
                     div2.style.textAlign = "right";
                     div2.style.paddingRight = "2px";
                     img = document.createElement('img');
                     img.src = "http://images.immobilo.de/bilder/d1/loading_24x24.gif";
                     img.style.width = "24px";
                     img.style.height = "24px";
                     div2.appendChild(img);
                     div.appendChild(div2);
                  }
               }
            }
                        
            var date = new Date();
            var timestamp = date.getTime();

            searchReq.open("GET", encodeURI('/wohnen/' + scrpt + '.php?time=' + timestamp + '&search=' + str + '&context=' + context + '&more=' + mehr + add), true); // CHANGE: /wohnen/
            searchReq.onreadystatechange = handleSearchSuggest; 
            
            searchReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
            searchReq.setRequestHeader("Cache-Control", "no-cache"); 
            
            searchReq.send(null);
         } else {
            document.getElementById('search_suggest_rahmen').style.display = "none"; 
         }
      }     
   }
}

// Handles KeyBoard
Tastencode_alt = 0;  
strsForced=false; // remember if streetsearch was activated silently
function  searchSuggestKey(event, context) {
   if(window.event) {
      evt = window.event; 
      Tastencode = evt.keyCode;
   } else {
      if(event) {
         Tastencode = event.which; 
      }
   }
   
   if(Tastencode == 9 && document.getElementById('suggest_tbody')) {
      var ch = document.getElementById('suggest_tbody').childNodes
      var t =  ch[suggestActiveId].firstChild.innerHTML; 
      var t2 = ch[suggestActiveId].getAttribute("param");
      var lat = ch[suggestActiveId].getAttribute("lat");
      var lng = ch[suggestActiveId].getAttribute("lng");
      
      setSearch(t,t2,lat,lng);
   }
   
   if (document.getElementById("STRS")) {
      
      //reset everything if streetsearch and not down/up/enter
      if (parseInt(document.getElementById("STRS").value)==1 && Tastencode!=13 && Tastencode!=40 && Tastencode!=38){
         if (strsForced){
            strsForced=false;
            document.getElementById("STRS").value=0;
         }
         document.getElementById('search_suggest_rahmen').style.display = "none";
         document.getElementById('search_suggest').innerHTML = '';
         document.getElementById('LAT').value=0;
         document.getElementById('LONG').value=0;
         closesuggest();
      }
   }
   
   if(Tastencode == 40) {
      suggestActiveId = suggestActiveId + 1; 
   } 
   if(Tastencode == 38) {
      if(suggestActiveId > 0) {
         suggestActiveId = suggestActiveId - 1; 
      } 
   } 
   if(Tastencode == 13) {
      
      if (document.getElementById('STRS')) {
         
         if (parseInt(document.getElementById("STRS").value)==1){
            if(document.getElementById('suggest_tbody')) {
               var ch = document.getElementById('suggest_tbody').childNodes
               if (ch[suggestActiveId]){
               var t =  ch[suggestActiveId].firstChild.innerHTML; 
               var t2 = ch[suggestActiveId].getAttribute("param");
               var lat = ch[suggestActiveId].getAttribute("lat");
               var lng = ch[suggestActiveId].getAttribute("lng");
               setSearch(t,t2,lat,lng);
               }else if (strsForced){
                  return true;
               }
               return true; // DRose: send form on first enter
               //return false;
            }else if (parseFloat(document.getElementById('LAT').value)==0 && parseFloat(document.getElementById('LONG').value)==0){
               searchSuggest(2, context); 
               return false;
            }else{
               return true;
            }
         }
      }
      
      
      
      if(document.getElementById('suggest_tbody')) {
         var ch = document.getElementById('suggest_tbody').childNodes
      } else {
         var ch = false;
         
         if (document.FM && document.FM.IDL) {
            
            if (document.FM.IDL.value != '' && parseInt(document.getElementById("STRS").value)!=1) {
               return true;
            }
            
         }
         
      }
      
      
      // handle suggestions 
      if (ch && (typeof ch === 'object' || typeof ch === 'function') && ch[suggestActiveId]) {
      
         if (ch[suggestActiveId].firstChild) {
            
            var ch_innerHTML = ch[suggestActiveId].firstChild.innerHTML;
            
            if (ch_innerHTML.indexOf('mehr...') > 0 ) {
               
               searchSuggest(1, context); 
               Tastencode_alt = 0;
               
            }
            else {
               
               var t2 = ch[suggestActiveId].getAttribute("param");
               setSearch(ch_innerHTML,t2);      
               var r = Tastencode_alt == Tastencode;  
               Tastencode_alt = 13;
               return true; // DRose: send form on first enter
               //return r;
               
            }
            
         }
         
         return false;
         
      }
      
      Tastencode_alt = 13; 
      
      //return true;
      
      //if nothing was found and user pressed enter do streetsearch
      Tastencode_alt=0;
      Tastencode=0;
      if (document.getElementById("STRS")) {
         var strs = document.getElementById("STRS");
         strs.value=1;
         strsForced=true;
         searchSuggest(2);
         return false; 
      }
   } else {
      Tastencode_alt = 0; 
   } 
   if(Tastencode == 38 || Tastencode == 40) {
      if(document.getElementById('suggest_tbody')) {
         var ch = document.getElementById('suggest_tbody').childNodes

         if(suggestActiveId >= ch.length) suggestActiveId = ch.length -1 
         for(var i = 0; i < ch.length; i++) {
            if(i == suggestActiveId) {
               ch[i].className = "suggest_link suggest_aktiv"; 
            } else {
               ch[i].className = "suggest_link"; 
            } 
         }
         ch[suggestActiveId].scrollIntoView(false); 
      } else {
         return false; 
      }
   } else {
      suggestActiveId = 0;
   }
   
   if (document.FM && document.FM.IDL && !nc('#topform_search')) {
      document.FM.IDL.value='';
   }
   
   // only reset value if last event was not 'enter key', depends on value changes above !
   if ((Tastencode !== 0) && nc('#topform_search')) {
      document.FM.IDL.value = '';
   }
   
   return true;
}


//Called when the AJAX response is returned.
function handleSearchSuggest() {
	
   if (searchReq.readyState == 4) {
      //        document.getElementById("Ergebnis").innerHTML += " .";
      suggestActive = false;
      if(Tastencode != 40 && Tastencode != 38 && Tastencode_alt != 13  ) {
         /*if(isIE() ) {
            if(document.FM) {
               document.FM.WAS.style.visibility = 'hidden'; 
               document.FM.TYP.style.visibility = 'hidden';
            } 
         }*/
         var str = searchReq.responseText.split("\n");
         
         if (document.getElementById('STRS')) {
        	 
        	 // HSF-705 remove loader-image when finished
        	 removeLoadAni();
        	 
            if (parseInt(document.getElementById("STRS").value)==1 && (str.length==0 || str[0].length==0)){
               if(geocoder == null){ 
                  /*var iframe = helper_get_mapframe();
                  if (typeof iframe === 'object'){
                     geocoder = iframe.geocoder;
                  }else{
                     return;
                  }*/
                  if (typeof GClientGeocoder != 'undefined') {
                    geocoder = new GClientGeocoder();
                  }
               }
               var search = document.getElementById("txtSearch").value;       
               search = search.replace(/([.,]+)/, " "); //remove all .,
               search = search.replace(/(str)(\s+|$)/i, "strasse "); //replace all "str" with tailing whitespace or lineend
               search = search.replace(/(straße)(\s+|$)/i, "strasse "); //replace all "straße" with tailing whitespace or lineend
               search = search.replace(/\s\s+/, " "); // replace all duplicate whitespace
               search = search.replace(/^\s+/, '').replace(/\s+$/,''); // trim
               
               geocoder.setBaseCountryCode('de');
               geocoder.getLocations(search, handleGeoCoderAnswer);
               return;
            }
         }


         getSearchSuggestBox(str);
      }
   }
}

var searchSuggestHandler = {
		
	iTimeout: 	100,
	oField: 	null,
	_oTimeout: 	null,
	bWait: 		false,
	query: 		'',
	template: 	'suggest_search',
	template_suffix: '.php',
	context: 	'',
	more: 		'',
	add: 		'',
	validateInput: function(str) {
		return (str && (isNaN(str) || !!str.match(/^\d{1,5}$/)));
	},
	delegate: function() {
		searchSuggestHandler.bWait = false;
		searchSuggestHandler.oField = searchSuggestHandler.oField || document.getElementById('txtSearch');  
	
		// determine new request condition 
		if (searchSuggestHandler.oField.value && 
			((searchSuggestHandler.query !== searchSuggestHandler.oField.value) || 
			(searchSuggestHandler.add !== add_was_typ(searchSuggestHandler.oField))	
		   ) 
		) {
			
			searchSuggestHandler.add = add_was_typ(searchSuggestHandler.oField);
			searchSuggestHandler.query = searchSuggestHandler.oField.value;
			// make request?
			if (searchSuggestHandler.validateInput(searchSuggestHandler.query)) {
				searchSuggestHandler.doRequest(searchSuggestHandler.query);
			}
		}
		// clear(ed) condition
		else if (!searchSuggestHandler.oField.value) {
			searchSuggestHandler.clearSuggest();
		}
		else {
			// don't send same request as before action
		}
	},
	clearSuggest: function(e) {
		searchSuggestHandler.oField.value = 
			searchSuggestHandler.query = searchSuggestHandler.add = '';
		searchSuggestHandler.hideSuggestBlock();
		searchSuggestHandler.doAbort();
	},
	hideSuggestBlock: function() {
		document.getElementById('search_suggest_rahmen').style.display = "none";
	},
	doGeocode: function(str){
		
		var toggle = document.getElementById("STRS") || null;
		
		if (toggle && Number(toggle) === 1) {
			searchSuggestHandler.template = 'suggest_gsearch';
			str = escape(str);
			suggestActive = false;
			
			if (document.getElementById("sucheText")){
                div = document.getElementById("sucheText");
                div2 = document.createElement('div');
                div2.id = "loadingdiv";
                div2.style.position = "absolute";
                div2.style.top = "8px";
                div2.style.left = "389px";
                div2.style.textAlign = "right";
                div2.style.paddingRight = "2px";
                img = document.createElement('img');
                img.src = "http://images.immobilo.de/bilder/d1/loading_24x24.gif";
                img.style.width = "24px";
                img.style.height = "24px";
                div2.appendChild(img);
                div.appendChild(div2);
             }
		}
        return false;
	},
	doAbort: function() {
		if (suggestActive) {
			searchReq.abort(); 
			suggestActive = false;
			searchReq = new XMLHttpRequest();
		}
	},
	doRequest: function(queryString) {
 
		if (currentFocus) {
		      currentFocus = null;
		      place_suggest = true;
		}
		
		// kill running request, if necessary
		searchSuggestHandler.doAbort();
		
		// check for geocoding request
		searchSuggestHandler.doGeocode(searchSuggestHandler.query);
		
		var args = [ 'time=' + (new Date()).getTime(), 
		     'search=' + searchSuggestHandler.query,
			 'context=' + (function(str) {
				 
				 if (str) {
					 if (nc('body').hasClass('frontpage')) {
						 return 'front';
					 }
				 }
				 return '';
				 
			 })(searchSuggestHandler.context),
			 'more' + searchSuggestHandler.more,
			 ];
		var url = "/wohnen/" + searchSuggestHandler.template + 
			 searchSuggestHandler.template_suffix + 
			 "?" + args.join('&') + searchSuggestHandler.add;
		
		searchReq.open("GET", encodeURI(url), true);
		searchReq.onreadystatechange = handleSearchSuggest; 
		searchReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		searchReq.setRequestHeader("Cache-Control", "no-cache"); 
		searchReq.send(null);
		
		suggestActive = true;
	}

};
var searchSuggestNG = (function(e) {
	if (typeof e === 'object' && !(e instanceof Array)) {
		if (searchSuggestHandler.bWait) {
			clearTimeout(searchSuggestHandler._oTimeout);
		}
		searchSuggestHandler._oTimeout = setTimeout(searchSuggestHandler.delegate, searchSuggestHandler.iTimeout);
		searchSuggestHandler.bWait = true;
	}
	else {
		// delegate deprecated calls
		searchSuggest(e, arguments[1] || null, arguments[2] || null);
	}
});

function getStreetKeyLeftBox(event, el){
   currentFocus = el;
   place_suggest = true;
   
   if(window.event) {
      evt = window.event; 
      Tastencode = evt.keyCode;
   } else {
      if(event) {
         Tastencode = event.which; 
      }
   }

   if (document.getElementById('suggest_tbody')){
      if(Tastencode == 9) { // tab
         var ch = document.getElementById('suggest_tbody').childNodes
         var value = ch[suggestActiveId].firstChild.innerHTML; 
         var idl = ch[suggestActiveId].getAttribute("param");
         var lat = ch[suggestActiveId].getAttribute("lat");
         var lng = ch[suggestActiveId].getAttribute("lng");
         return setStreetLeftBox(el, value, idl, lat, lng);
      }
   }
   if(Tastencode == 13) { // enter
      if (document.getElementById('suggest_tbody')){
         var ch = document.getElementById('suggest_tbody').childNodes
         var value = ch[suggestActiveId].firstChild.innerHTML; 
         var idl = ch[suggestActiveId].getAttribute("param");
         var lat = ch[suggestActiveId].getAttribute("lat");
         var lng = ch[suggestActiveId].getAttribute("lng");
         return setStreetLeftBox(el, value, idl, lat, lng);
      }else{         
         var search = el.value;
         var a1_name = "";
         var a2_name = "";
         var ort = "";
         //ort = nc('#sidebar-right-searchform input[name=WO]').val();
         if (nc('span#alvl_1').html()!=null) a1_name = nc.trim(nc('span#alvl_1').html().toLowerCase());
         if (a1_name=='berlin' || a1_name=='bremen' || a1_name=='hamburg'){
            ort = a1_name;
         }else{
            if (nc('span#alvl_2').html()!=null) a2_name = nc('span#alvl_2').html().toLowerCase();
            else a2_name = nc('#sidebar-right-searchform input[name=WO]').val();
            ort = nc.trim(a2_name);
         }
         
         search = search + ", " + ort;
         return getStreetFromLocal(search);
      }
   }
   if (document.getElementById('suggest_tbody')){
      if(Tastencode == 40 || Tastencode == 38) {
         if(Tastencode == 40) { // down
            suggestActiveId = suggestActiveId + 1; 
         }else if(Tastencode == 38 && suggestActiveId > 0) { // up
            suggestActiveId = suggestActiveId - 1;
         }
         
         var ch = document.getElementById('suggest_tbody').childNodes
   
         if(suggestActiveId >= ch.length) suggestActiveId = ch.length -1 
         for(var i = 0; i < ch.length; i++) {
            if(i == suggestActiveId) {
               ch[i].className = "suggest_link suggest_aktiv"; 
            } else {
               ch[i].className = "suggest_link"; 
            } 
         }
         ch[suggestActiveId].scrollIntoView(false);
      }else{
         suggestActiveId=0;
      }
   }
   if (Tastencode != 40 && Tastencode != 38){
      suggestActiveId=0;
      closesuggest();
   }
   return true;
}

function getStreetFromLocal(search){
   str = escape(search);            
   
   var date = new Date();
   var timestamp = date.getTime();
   
   searchReq.open("GET", encodeURI('/wohnen/suggest_gsearch.php?time=' + timestamp + '&search=' + str), true); // CHANGE: /wohnen/
   searchReq.onreadystatechange = function(){ handleStreetFromLocal(search); }; 
   
   searchReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
   searchReq.setRequestHeader("Cache-Control", "no-cache"); 
   
   searchReq.send(null);
   
   return false;
}

function handleStreetFromLocal(search){
   if (searchReq.readyState == 4) {
      var str = searchReq.responseText.split("\n");
      if (str.length==0 || str[0].length==0){
         initGeoSearch(search);
      }
      getSearchSuggestBox(str);
   }
}

function initGeoSearch(search){
   if(geocoder == null){ 
      /*var iframe = helper_get_mapframe();
      if (typeof iframe === 'object'){
         geocoder = iframe.geocoder;
      }else{
         return false;
      }*/
      if (typeof GClientGeocoder != 'undefined') {
         geocoder = new GClientGeocoder();
      }
   }
   
   search = search.replace(/([.,]+)/, " "); //remove all .,
   search = search.replace(/(str)(\s+|$)/i, "strasse "); //replace all "str" with tailing whitespace or lineend
   search = search.replace(/(straße)(\s+|$)/i, "strasse "); //replace all "straße" with tailing whitespace or lineend
   search = search.replace(/\s\s+/, " "); // replace all duplicate whitespace
   search = search.replace(/^\s+/, '').replace(/\s+$/,''); // trim
   
   geocoder.setBaseCountryCode('de');
   geocoder.getLocations(search, handleGeoCoderAnswer);
   
   return false
}

function setStreetLeftBox(el, value, idl, lat, lng){
   var tmp = value.split(" ["); 
   var r = tmp[0]; 
   el.value = r;
   nc('#sidebar-right-searchform input[name=IDL]').val(idl);
   
   if (!isNaN(lat) && !isNaN(lng)){
      // test if elements actually exist
      if (nc('#sidebar-right-searchform input[name=LAT]') && nc('#sidebar-right-searchform input[name=LONG]')) {
         nc('#sidebar-right-searchform input[name=LAT]').val(lat);
         nc('#sidebar-right-searchform input[name=LONG]').val(lng);
      }
   }
   suggestActiveId=0;
   closesuggest();
   
   onch(el);
   return false;
}

function handleGeoCoderAnswer(response){
   if (!response || response.Status.code != 200) {
      // unable to geocode address
      if (strsForced){  
        // set streetsearch to off, if it was forced before but couldn´t find anything
         document.FM.STRS.value=0;
         strsForced=false;
         document.FM.submit();
      }
      if (response.Status.code == 602){
         if (currentFocus!=null){
            suggestActiveId=0;
            closesuggest();
            alert('Diese Adresse wurde leider nicht gefunden.');
         }
      }
   } else {
      // send response to server
      params="json=" + escape(JSON.stringify(response));
      
      searchReq.open("POST", "/wohnen/suggest_gsearch.php", true);

      searchReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
      searchReq.setRequestHeader("Content-length", params.length+10);
      searchReq.setRequestHeader("Connection", "close"); 
      searchReq.onreadystatechange = null;
      //searchReq.onreadystatechange = function processXMLResponse() { getSearchSuggestBox(searchReq.responseText.split("\n")); };
      searchReq.send(params);
      
      out='';
      // fill suggest box
      for (var i=0; i < response.Placemark.length; i++){
         var street=zip=city='';
         placem = response.Placemark[i];
         
         try {
            if (placem.AddressDetails.Accuracy>=6){
               placemLoc = placem.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality;
               if (placemLoc.DependentLocality!=undefined){
                  if (placemLoc.DependentLocality.Thoroughfare.ThoroughfareName!=undefined)
                     street =placemLoc.DependentLocality.Thoroughfare.ThoroughfareName;
                  if (placemLoc.DependentLocality.PostalCode!=undefined && placemLoc.DependentLocality.PostalCode.PostalCodeNumber!=undefined)
                     zip = placemLoc.DependentLocality.PostalCode.PostalCodeNumber;
               }else{
                  if (placemLoc.Thoroughfare.ThoroughfareName!=undefined)
                     street =placemLoc.Thoroughfare.ThoroughfareName;
                  if (placemLoc.PostalCode!=undefined && placemLoc.PostalCode.PostalCodeNumber!=undefined)
                     zip =    placemLoc.PostalCode.PostalCodeNumber;
               }
               city =   placemLoc.LocalityName;
               
               street =street.replace(/^\s+/, '').replace(/\s+$/,'');
               zip =    zip.replace(/^\s+/, '').replace(/\s+$/,'');
               city =   city.replace(/^\s+/, '').replace(/\s+$/,'');
               loc = street+', '+zip+' '+city;
               
               lat=placem.Point.coordinates[1];
               lng=placem.Point.coordinates[0];
               
               if (street.length>0 && city.length>0 && (lat == parseFloat(lat)) && (lng == parseFloat(lng))){
                  out+=loc+"\t0\t\t"+lat+"\t"+lng+"\n";
               }
            }
         }catch(err){}
      }
      if (out==null || out.length==0){
         if (currentFocus!=null){
            suggestActiveId=0;
            closesuggest();
            alert('Diese Adresse wurde leider nicht gefunden.');
         }
      }
      else getSearchSuggestBox(out.split("\n"));
   }
   removeLoadAni();
}

function getSearchSuggestBox(str){
   var ss = document.getElementById('search_suggest')
   var ssa = document.getElementById('search_suggest_rahmen'); 
   // ss.innerHTML = '';
   ssa.style.display="block";
   
   placesuggest_final();
   
   if(str.length > 22) {
      ssa.style.overflow='auto'; 
      ssa.style.overflowX='hidden';
      ssa.style.height='400px';
      // FIXME: if nc is not defined ...
      if (nc('body').hasClass('frontpage')) {
         ssa.style.width='410px';
      }
      else {
         ssa.style.width='280px';   
      }
      ssa.style.border='1px solid black';
      ss.style.border='1px none black';
   } else {
      ss.style.border='1px solid black';
      ssa.style.border='1px none black';
      ssa.style.overflow='visible';
   }
   // apply width for table with css, not hardcode it inline 
   var sb = (str.length > 22) ? 'class="scrollbar"' : ''; 
   /*
   if(str.length > 22) {
      var sb = "255px"; 
   } else {
      var sb = "279px";    
   }
   */
   ss_innerHTML ='<table id="suggest_table" cellpadding="0" cellspacing="0" border="0" ' + sb + '>'; 
   ss_innerHTML +='<tbody id="suggest_tbody">'; 
   for(i=0; i < str.length - 1; i++) {
      //Build our element string.  This is cleaner using the DOM, but
      //IE doesn't support dynamically added attributes.
      var ind = str[i].split("\t");  
      var data=ind[0].split(" [");
/***
      var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
      suggest += 'onmouseout="javascript:suggestOut(this);" ';
      suggest += 'onclick="javascript:setSearch(\''+data[0]+'\',\''+ind[1]+'\');" ';
      var cl = (suggestActiveId == i) ? cl = "suggest_aktiv" : cl = ''; 
      suggest += 'class="suggest_link '+cl+'" param="'+ind[1]+'"><div class="suggest_name" param="'+ind[1]+'">' + data[0]+'</div>';
      if(data[1]) {
         suggest += '<div class="suggest_count" param="'+ind[1]+'">&nbsp;&nbsp;['+data[1]+'</div>';
      }
      suggest += '</div>';
***/
      var suggest ='<tr onmouseover="javascript:suggestOver(this);" '; 
      suggest += 'onmouseout="javascript:suggestOut(this);" ';
      if (currentFocus==null){
         suggest += 'onclick="javascript:setSearch(\''+data[0]+'\',\''+ind[1]+'\',\''+ind[3]+'\',\''+ind[4]+'\');" ';
      }else{
         suggest += 'onclick="javascript:setStreetLeftBox(currentFocus,\''+data[0]+'\',\''+ind[1]+'\',\''+ind[3]+'\',\''+ind[4]+'\');" ';
      }
      var cl = (suggestActiveId == i) ? cl = "suggest_aktiv" : cl = '';
      var param='param="'+ind[1]+'" lat="'+ind[3]+'" lng="'+ind[4]+'"';
      suggest += 'class="suggest_link '+cl+'" '+param+'><td '+param+'>' + data[0]+'</td>'; 
      suggest += '<td align="right" class="right" '+param+'>&nbsp;'
      if(data[1]) {
         suggest += '['+data[1];
      } 
      suggest += '</td></tr>';
      ss_innerHTML += suggest ;
   
   }
   if(str.length == 22) {
      var cl = (suggestActiveId == i) ? cl = "suggest_aktiv" : cl = '';
      ss_innerHTML += '<tr class="suggest_link '+cl+'" ><td colspan=2><a href="#" onclick="searchSuggest(1); return false;" style="display: block; width: 100%;" title="Klicken Sie hier um alle Treffer anzuzeigen.">&nbsp;&nbsp;mehr...</a></td></tr>'; 
   }
   
/* var strs=document.getElementById("STRS");
   if (str=="" && strs.value==0) forceStreetSearch(false);*/

   ss.innerHTML = ss_innerHTML + "</tbody></table>";
   suggestActive = false;   
   removeLoadAni();
}

function removeLoadAni(){
   var div = document.getElementById('sucheText');
   if (document.getElementById('loadingdiv')) {
      var div2 = document.getElementById('loadingdiv');
      div.removeChild(div2);
   }
}

//Mouse over function
function suggestOver(div_value) {
   div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
   div_value.className = 'suggest_link';
}
//Click function
function setSearch(value,idl,lat,lng) {
   var tmp = value.split(" ["); 
   var r = tmp[0]; 
   document.getElementById('txtSearch').value = r;
   document.getElementById('IDL').value = idl;
   
   if (!isNaN(lat) && !isNaN(lng)){
	   // test if elements actually exist
	   if (document.getElementById('LAT') && document.getElementById('LONG')) {
		   document.getElementById('LAT').value = lat;
		   document.getElementById('LONG').value = lng;
	   }
	   
   }
   document.getElementById('search_suggest_rahmen').style.display = "none";
   document.getElementById('search_suggest').innerHTML = '';
   closesuggest();
}

function placesuggest() {
   place_suggest = true; 
}

function i_getLeft(ireds_l) {
   if (ireds_l.offsetParent) return (ireds_l.offsetLeft + i_getLeft(ireds_l.offsetParent));
   else return (ireds_l.offsetLeft);
}

function i_getTop(ireds_l) {
        if (ireds_l.offsetParent) return (ireds_l.offsetTop + i_getTop(ireds_l.offsetParent));
        else return (ireds_l.offsetTop);
}

function i_getFromId(e) {
   if(e) {
      if(e.tagName == "FORM") {  
         return e; 
       }
      else {   
         return i_getFromId(e.parentNode); 
      }
   } else {
      return false; 
   }
}

function add_was_typ(e) {
   var f = i_getFromId(e);
//    alert(f);   
   var r = ''; 
   if(f.elements['WAS']) {
      r = r + "&WAS="+f.elements['WAS'].value; 
   }
   if(f.elements['TYP']) {
      r = r + "&TYP="+f.elements['TYP'].value; 
   }
   return r; 
}

var map_pos_x = 0 ;
var map_pos_y = 0 ;
var lastfix = ''; 

function get_map_pos() {
      map_pos_x = i_getLeft(document.getElementById("map_iframe"));
      map_pos_y = i_getTop(document.getElementById("map_iframe"));
} 

function rahmen(e,was) {
   
   var f = (was == 1) ? '1px solid #3362A8' : '1px solid #CCCCCC';
   var h = (was == 1) ? '1px solid #3362A8' : '1px solid #FFFFFF';
    
   if(document.getElementById(e)) {
      document.getElementById(e).style.borderTop = f;
      document.getElementById(e).style.borderBottom = h;
      document.getElementById(e).style.borderLeft = h;
      document.getElementById(e).style.borderRight = h;
   }
   if (was==1) nc('#func_'+e).show();
   else nc('#func_'+e).hide();
} 

function rahmen_bg(e, was){
   var bg = (was == 1) ? '#f9f9f9' : '#ffffff';
   if(document.getElementById(e)) {
      document.getElementById(e).style.backgroundColor = bg;
   }

   rahmen(e, was);
}

function placesuggest_final() {
   
   if(place_suggest) {
      var sg = document.getElementById("search_suggest_rahmen"); 
      if (currentFocus==null){
         var left = i_getLeft(document.getElementById('txtSearch'));
         var top = i_getTop(document.getElementById('txtSearch'))+17;
      }else{
         var left = i_getLeft(currentFocus)-3;
         var top = i_getTop(currentFocus)+19;
      }
       
      sg.style.top = top + "px";   
      sg.style.left = left + "px";  
   }
   
    place_suggest = false;
     
} 

function chdup(t) {
   var a = t.name; 
   var v = t.value; 
   var wie = t.checked; 
   for(var i = 0; i < document.BOXFORM.elements.length;i++) {
      var e = document.BOXFORM.elements[i]; 
      if(e.name == a && e.value == v) {
         e.checked = wie; 
      }
   }
   var b = document.BOXFORM.elements[a]; 
}

function closesuggest(e) {
   var trgtid = '';
   if (typeof e !== 'undefined') {
      var trgt = e.target || false;
      trgtid = (trgt !== false) ? trgt.id : false;
   }
   // do not close if hausbau-select is clicked
   if(document.getElementById('search_suggest_rahmen').style.display != "none" && trgtid!='selectbtn') {
      document.getElementById('search_suggest_rahmen').style.display = "none";
      document.getElementById('search_suggest').innerHTML = '';
   }
    /*if(isIE()) {
     if(document.FM) {
      document.FM.WAS.style.visibility = 'visible'; 
      document.FM.TYP.style.visibility = 'visible';
     }
    } */
}

addAnEvent(document, 'click',closesuggest);



////////////////////////////////////////////

var suggestActive = false; 
var suggestStr = ''; 
var suggestActiveId = 0;
var Tastencode = 0;

////////////////////////////////////////////

function makeniceurl(wo) {
  var url = '/wohnen'; 
  
  // launch popunder
  popunder(true);
  
  if(wo == 'BOXFORM') {
/** 
   var f = document.BOXFORM; 
   url = url + "/" + f.WAS.value.toLowerCase(); 
   url = url + "/all?" ;  
   if(f.IDL.value != '') url = url + "IDL=" + f.IDL.value + "&"; 
   if(f.WO.value != '')  url = url + "WO=" + encodeURI(f.WO.value) + "&";
   window.location.href = url; 
   return false; 
**/
   //check if it´s a streetsearch and submit form
      if (is_search() &&
         document.BOXFORM.STRASSE.value!='Straße' && document.BOXFORM.STRASSE.value!="" &&
      document.BOXFORM.LAT.value!="" && document.BOXFORM.LONG.value!=""){
      onch(document.BOXFORM.STRASSE);
      return false;
   }else{
   document.BOXFORM.submit(); 
  }
  }
   return false;
} 

////////////////////////////////////////////
//
// Bild Scroller
/////////////////////////////////////////////


var scrolltimer = 0; 
var scrollwie = 0; 



function bscroll(wie) {
    scrollwie = wie; 
   if(wie == 0) {
      window.clearInterval(scrolltimer); 
      scrolltimer = 0; 
   } else {
   if(scrolltimer == 0) 
      scrolltimer = window.setInterval('dobscroll(0)',50); 
      dobscroll(); 
   }
} 

function dobscroll(wie) {
    if(wie == 0 ) wie = scrollwie; 
   var pos = document.getElementById("Rahmeninhalt").style.marginLeft; 
   var fc = document.getElementById("Rahmeninhalt").firstChild; 
   pos = pos.replace(/px/,''); 
   var tmp = 1 * pos + scrollwie
   if(tmp < 15 &&  fc.offsetWidth + tmp > 350) {
      document.getElementById("Rahmeninhalt").style.marginLeft = tmp + 'px'; 
   } 
   
}


//////////////////////////////////////////////

function pop_ort_detail() {
   document.getElementById("ort_detail_pos").style.display = "block";
   document.getElementById("ort_detail_rahmen").style.display = "block"; 
}


function pop_plz_detail() {
   ajax_call("/wohnen/a_plzauswahl.php"); // CHANGE: /wohnen/ 
} 

function pop_idl_detail() {
        ajax_call("/wohnen/a_idlauswahl.php"); // CHANGE: /wohnen/
}

function reset_wo(doNotResetIDL) {
   // search.boxlinks
   document.BOXFORM.LAT.value=0;
   document.BOXFORM.LONG.value=0;
   if (document.BOXFORM.PLZ) document.BOXFORM.PLZ.value='';
   if (!doNotResetIDL) {
      document.BOXFORM.IDL.value=0;
   }
   for(var i = 0; i < document.BOXFORM.elements.length;i++) {
      var e = document.BOXFORM.elements[i]; 
      if(e.name == "PLZS[]" || e.name == "IDLS[]") {
         e.checked = false;
      }
   }
   return true; 
}

function reset_strasse(){
   document.BOXFORM.STRASSE.value='Straße';
   set_color('#sidebar-searchfield_str','#666666');
   nc('#sidebar-right-searchform input[name=LAT]').val('');
   nc('#sidebar-right-searchform input[name=LONG]').val('');
}
var last_ajax_reload = ''; 
/*
// restore dynamic search
if (window.location.hash && !last_ajax_reload) {
    ajax_call('/wohnen/a_suche.php?' + window.location.hash);
    // ajax_reload();
}
*/
function ajax_reload() {
  var a = new Array(); 
  if(document.BOXFORM) {
    for(var i = 0 ; i < document.BOXFORM.elements.length; i++) {
   e = document.BOXFORM.elements[i];
   // <!--Für Indextool -->
   make_index_ajax(e.name,e.value); 
   if(e.type == 'checkbox') {
      if(e.checked) {
        a.push(e.name + '=' + encodeURI(e.value));
      }
   } else {
      if (e.value != '') {
        a.push(e.name + '=' + encodeURI(e.value)); 
       
      } 
   }
    } 
  }
  /*
  if (window.location.hash && !last_ajax_reload) {
     var url = "/wohnen/a_suche.php?"+window.location.hash;
     }
  else {
  */
  var url = "/wohnen/a_suche.php?"+a.join('&'); // CHANGE: /wohnen/
  if(last_ajax_reload != url) { 
     ajax_call(url);
     place_loader('#spalte2');
     mapResizeLoadingAnimation({'show': true});

     /*
    document.getElementById('loader').style.display = 'block';
    document.getElementById('loader').style.left = i_getLeft(document.getElementById('spalte2')) + 'px'; 
    document.getElementById('loader').style.top = i_getTop(document.getElementById('spalte2')) + 'px';
    document.getElementById('loader').style.height = document.getElementById('spalte2').offsetHeight + 'px';
    document.getElementById('loader').style.width = document.getElementById('spalte2').offsetWidth+ 'px';
    */
    last_ajax_reload = url; 
  } 
/*  
  // provide bookmarking / history of dynamic search filter changes
  // var url = 'http://www.heimstar.net/wohnen/a_suche.php?LAT=51.412483864171726&LONG=11.889266967773438&WO=-&TYP=WOHNUNG&WAS=MIETE&RADIUS_control=true&RADIUS_user_search=0&RADIUS=3.6&P=3&search_typ=sidebar&OFFSET=0&t=1223917885063';
  var hash = url.substr(url.indexOf('?') + 1, url.length);
  window.location.hash = encodeURI(hash);
  // window.location.hash = encodeURI(last_ajax_reload);
*/
}



////////////////////////////////////////////////

var req; 

 function xmlOpen(method, url, toSend, responseHandler)
 {
     if (window.XMLHttpRequest)
     {
         // browser has native support for XMLHttpRequest object
         req = new XMLHttpRequest();
                        if (req.overrideMimeType) {
                                req.overrideMimeType('text/xml');
         }
     }
     else if (window.ActiveXObject)
     {
         // try XMLHTTP ActiveX (Internet Explorer) version
         req = new ActiveXObject("Microsoft.XMLHTTP");
     }

     if(req)
     {
         req.onreadystatechange = responseHandler;
         req.open(method, url, true);
                 // wegen OPERA 8 auskommentiert!
                        try {
                 req.setRequestHeader("content-type","application/x-www-form-urlencoded");
                        }
                        catch(e) {
                        }
         req.send(toSend);
     }
     else
     {
         alert('Your browser does not seem to support XMLHttpRequest.');
     }
 }


function ajax_back() {
     if (req.readyState == 4)
     {
         // Make sure the status is "OK"
         if (req.status == 200)
         {
             var ajax = req.responseXML.getElementsByTagName('ajax');

                         var html_teil = req.responseXML.getElementsByTagName('html');
                         var js_teil = req.responseXML.getElementsByTagName('js');

                        for(i=0; i < html_teil.length; i++) {
                                var node = html_teil.item(i);
                                var node_id = node.getAttribute('html_id');
                                var append_node = node.getAttribute('append');
                                if(document.getElementById(node_id)) {
                                        if(append_node==1) {
                                                document.getElementById(node_id).innerHTML += node.firstChild.nodeValue
                                        }
                                        else {
                                                document.getElementById(node_id).innerHTML = node.firstChild.nodeValue
                                        }
                                }
                        }

                        for(i=0; i < js_teil.length; i++) {
                                var node = js_teil.item(i);
                                var node_id = node.getAttribute('call');
                                //eval("document.X_"+node_id+" = 'sss' ;");
                                jscode = node.firstChild.nodeValue.replace(/\n/g,';');
                                jscode = jscode.replace(/\r/,';');
                                // jscode = jscode.replace(/"/g,'\\"');
                                // eval(node_id+" = new Function('"+jscode+"');");
            var f = "function "+node_id+"() { "+jscode+" ;} ;"; 
            eval(f);
                                eval(node_id+"();");
                        }
            			
                 }
         else
         {
             alert("There was a problem retrieving the XML data:\n" + req.statusText);
         }
     }
 }

 function ajax_call(url){
    url = append_timestamp_to_ajax_url(url);
    xmlOpen("GET", url, null, ajax_back);
 }
 
 function append_timestamp_to_ajax_url(url){
    var Jetzt = new Date();

    if(url.indexOf("?")>0) {
       url=url + "&t="+Jetzt.getTime();
    }
    else {
       url=url + "?t="+Jetzt.getTime();
    }
    return url;
 }

 function ajax_post(url,post_data) {
     post_data += '&_REFERER='+escape(this.location.href);
     xmlOpen("POST",url,post_data,ajax_back);
 }

/////////////////////////////////////////////////////////////////////////////77

// 'slider_SIZE',{$AREA_MIN},{$AREA_MAX},'SFROM','STO',5);

var slcontrollers = new Array(); 


function set_sl_values() {
   x = 1; 
}

function resetSlider(slider,fr,to,wie){
   min = nc('#'+slider).data('min.slider').x;
   max = nc('#'+slider).data('max.slider').x;
   handles = nc('#'+slider).data('handles.slider');
   if (nc('#'+slider).slider("value",0)!=min || nc('#'+slider).slider("value",1)!=max){
      nc('#'+slider).slider("moveTo",min,0,true)
      nc('#'+slider).slider("moveTo",max,1,true);
      set_sl_text(slider,wie,min,max,fr,to);
      absenden();
   }
}

function resetSliderRadius(r, opts) {
   
   radius = (parseFloat(r)) ? parseFloat(r) : 2; // (window.frames['map_iframe'].map) ? window.frames['map_iframe'].get_current_radius(window.frames['map_iframe'].map) : 2;
   usersearch = (typeof opts === 'object' && opts.usersearch) ? opts.usersearch : 0;
   
   document.BOXFORM.RADIUS_control.value = 'false';
   document.BOXFORM.RADIUS.value  =  Math.max(Math.min(radius,20),1) ; 
   document.BOXFORM.RADIUS_user_search.value = usersearch;
   nc("#slider_RADIUS").slider('moveTo', 10 * radius, 0); // factor 10
   document.BOXFORM.RADIUS_control.value = 'true';
   
   if (!usersearch) {
      nc('a#reset-slider-img').removeClass('active');
      absenden();
   }
   else {
      nc('a#reset-slider-img').addClass('active');
   }
   
   
}

function add_sl_contoller(sid,mi,ma,fr,to,step) {
//  nc("#example").slider({
//  min:20,max:200,stepping:10,changevvv:function(e,ui){alert(ui.value)},
//  slide:function(e,ui)
//  {nc("#xx").html(nc("#example").slider('value',0)+'-'+nc("#example").slider('value',1))},
//  range:true,handles:[{start:40},{start:180}] });
//   });

var tov = ma; 
var frv = mi; 
if(document.getElementById(fr).value != '') frv = document.getElementById(fr).value;   
if(to != '') { 
if(document.getElementById(to).value != '') tov = document.getElementById(to).value;
if(frv < mi)  {frv = mi; document.getElementById(fr).value = frv; }
if(tov < mi+step) { tov = mi+step; document.getElementById(to).value = tov;} 
if(frv > ma)  {frv = ma-step*3; document.getElementById(fr).value = frv; }
if(tov > ma) { tov = ma; document.getElementById(to).value = tov;}
nc("#"+sid).slider({min:sl_parse_value_back(sid,mi),max:sl_parse_value_back(sid,ma),stepping:step,handles:[{start:sl_parse_value_back(sid,parseInt(frv))},{start:sl_parse_value_back(sid,parseInt(tov))}], 
 slide:function(e,ui) { set_sl_text(this.id,true,mi,ma,fr,to)  } , 
   change:function(e,ui) { set_sl_text(this.id,true,mi,ma,fr,to); absenden(); },  
 range:true } ) ; 
} else {
 if (sid!="slider_RADIUS"){
frv = frv * 10; 
nc("#"+sid).slider({min:mi*10,max:ma*10,stepping:1,handles:[{start:frv}], 
 slide:function(e,ui) { set_sl_text(this.id,false,mi,ma,fr,to)  } , 
 change:function(e,ui) { set_sl_text(this.id,false,mi,ma,fr,to); absenden();  }, 
 range:false } ) ; 
 }
 /* exception for radius slider*/
 else{
 frv = frv * 10; 
 nc("#"+sid).slider({min:mi*10,max:ma*10,stepping:1,handles:[{start:frv}], 
 slide:function(e,ui) { set_sl_text(this.id,false,mi,ma,fr,to)  } , 
    change:function(e,ui) { set_sl_text(this.id,false,mi,ma,fr,to); absenden_check();  }, 
 range:false } ) ; 
 }
}
} 


function round_on(val,step) {
	return step*Math.round(val/step);
}

function sl_parse_value(hid,value) {
if(hid=="slider_PRIZE") {
	if(index_data['art']=="KAUF") {
		if(value<100000)
			return round_on(100000+(value-100000)*2,10000);
		else if(value<400000)
			return round_on(400000+(value-400000)*1,5000);
		else if(value<700000)
			return round_on(400000+(value-400000)*2,10000);
		else
			return round_on(1000000+(value-700000)*5,25000);
	}
	else {
		if(value<250)
			return round_on(250+(value-250)*5,50);
		else if(value<1000)
			return round_on(1000+(value-1000)*1,10);
		else
			return round_on(1000+(value-1000)*5,50);
	}
}
else
	return value;
}

function sl_parse_value_back(hid,value) {
if(hid=="slider_PRIZE") {
	if(index_data['art']=="KAUF") {
		if(value<100000)
			return round_on(100000+(value-100000)/2,10000);
		else if(value<400000)
			return round_on(400000+(value-400000),5000);
		else if(value<700000)
			return round_on(400000+(value-400000)/2,10000);
		else
			return round_on(550000+(value-700000)/5,25000);
	}
	else {
		if(value<250)
			return round_on(250+(value-250)/5,50);
		else if(value<1000)
			return round_on(1000+(value-1000),10);
		else
			return round_on(1000+(value-1000)/5,50);
	}
}
else
	return value;
}

function sl_format(arg) {
	arg = arg+'';
	if(arg<1000)
		return arg;
	else
		return arg.substr(0, arg.length-3)+'.'+arg.substr(arg.length-3, 3);
}

function set_sl_text(hid,wie,min,max,fr,to) {
var txt = ''; 
var a = " "+document.getElementById(hid+'_text').getAttribute('title'); 
var frv = ''; 
var tov = '';
if(wie) {//alles au�er Radius
 frv = sl_parse_value(hid,parseInt(nc('#'+hid).slider('value',0))); 
 tov = sl_parse_value(hid,parseInt(nc('#'+hid).slider('value',1)));
 if(frv > min && tov < max) {
    txt = sl_format(frv)+' - '+sl_format(tov)+a; 
 } else {
    txt = "unbegrenzt" 
    if(frv > min) {
       txt = ' ab '+sl_format(frv)+a; 
    } else {
       frv = '';
    } 
    if(tov < max) {
       txt = ' bis '+sl_format(tov)+a;
    } else {
       tov = '';
    } 
 }
 if(frv == tov) {
    txt = sl_format(frv)+a; 
 } 
 document.getElementById(fr).value = frv; 
 document.getElementById(to).value = tov; 
} else {//Radius-Slider
 frv = sl_parse_value(hid,parseInt(nc('#'+hid).slider('value',0))) / 10;
 if(frv > min ) {
     txt = sl_format(frv) + a;
 } else {
    frv = ''; 
 }
 document.getElementById(fr).value = frv;
} 
//HSF-532
//alert(txt);
if(txt==a)
 txt = "unbegrenzt";
nc('#'+hid+'_text').html(txt); 
}

function addAnEvent(el, evname, func) {
if (el.attachEvent) { // IE
el.attachEvent("on" + evname, func);
} else if (el.addEventListener) { // Gecko / W3C
el.addEventListener(evname, func, true);
} else {
el["on" + evname] = func;
}
}


//////////////////////////////////////////////////////////////////////////////////

var rfinal = new Array(); 

function run_final() {
   for(var i = 0; i < rfinal.length; i++) {
      rfinal[i].run(); 
   } 
} 


/////////////////////////////////////////////////////////////////////////////////

function empty_field(f,w) {
   if(document.getElementById(f)) {
      if(document.getElementById(f).value == w) {
         document.getElementById(f).value = ''; 
      }
      else {
         document.getElementById(f).select();
      }
   }
} 

/**
 * restore sane default for an input field, uses "numeric" as test criteria  
 * @param elt - form input object
 * @param replace - default to set, if test fails  
 * @return void
 */
function empty_field_restore(elt, replace) {
   
   var value = elt.value;
   
   if (value == '' || isNaN(value)) {
   
      elt.value = replace;
      
   }
   
}

/////////////////////////////////////////////////////////////////////////////////

function content_scroll(htmlid, intHeight) {
   this.objElement = document.getElementById(htmlid);
   var self = this;
   this._y = 0;
   this.objElement.style.top  = "0px";
   this.setPosition = function(intPos, y) {
      if (intPos > 0) intPos = 0;
      if (intPos < intHeight - this.objElement.offsetHeight)
            intPos = intHeight - this.objElement.offsetHeight;
      if (((this._y*-1) < this.objElement.offsetHeight) || (y > 0)) {
            this._y = intPos;
            this.objElement.style.top  = this._y +"px";
      }
   };
   this.scrollY = function(y) { this.setPosition(this._y + y, y); };
   this.start = function(y) { 
      this.scrollTimer = window.setInterval( function() { self.scrollY(y); }, 25 ); 
   };
   this.stop = function() { 
      if (this.scrollTimer) window.clearInterval(this.scrollTimer); 
   };
};

function get_viewport() {
   viewport = new Array();
   if (typeof window.innerWidth != 'undefined') {
      viewport[0] = window.innerWidth;
      viewport[1] = window.innerHeight;
      viewport[2] = window.pageYOffset;
   }
   else if (typeof document.documentElement != 'undefined' && 
          typeof document.documentElement.clientWidth !='undefined' && 
          document.documentElement.clientWidth != 0)
   {
       viewport[0] = document.documentElement.clientWidth;
       viewport[1] = document.documentElement.clientHeight;
       viewport[2] = document.documentElement.scrollTop; 
   }
   return viewport;
} 
 
function show_rec_box(htmlid,w,h,call) {
   div = document.getElementById(htmlid);
   div.style.width = w+"px";
   div.style.height = h+"px";
   vp = get_viewport();
   div.style.top = parseInt(((vp[1]/2) - (h/2))+vp[2])+"px";
   div.style.left = parseInt((vp[0]/2) - (w/2))+"px";
   div.style.display = "block";
   if (call != "") {
      ajax_call(call); 
   }
}

function close_rec_box(htmlid) {
   document.getElementById(htmlid).style.display = "none";
}

function send_form_ajax(formid,script) {
      str = form_serialize(formid);
      ajax_post(script,str);  
}

function form_serialize(htmlid) {
   form = document.getElementById(htmlid);
   values = new Array();
   for (var i = 0; i < form.elements.length; i++) {
      elem = form.elements[i];
      switch(elem.type) {
         case "checkbox":
            if (elem.checked) {
               values.push(elem.name+"=on");
            }
            else {
               values.push(elem.name+"=off");
            }
         break;
         default:
             values.push(elem.name+"="+elem.value);
         break;
      }
   } 
   return values.join("&");
}

function set_captcha(src) {
   if (document.getElementById('captcha_image')) {
      document.getElementById('captcha_image').src='/wohnen/captcha_image.php?img='+src; 
   }
}

function clean_rec_form(w,h) {
   document.getElementById("captcha_image").src = "http://images.immobilo.de/bilder/loading.gif";
   ajax_call('/wohnen/captcha_regenerate.php?WIDTH='+w+'&HEIGHT='+h); 
   document.getElementById("rec_captcha").value="";
}

function log(t) {
// document.getElementById("debug").innerHTML = t 
//    + "<br>"+document.getElementById("debug").innerHTML.substring(0,500);; 
} 

/////////////////////////////////////////////////////////////////

function setimg(ig,w,h) {
   
   if(ig.height > 0) {
      var igh = document.getElementById("dest_"+ig.id);  
      var f = ig.width / ig.height 
      if(f > 1) {
         igh.width = Math.min(w,ig.width);
         igh.height = Math.round(igh.width / f );  
      } else {
         igh.height = Math.min(h,ig.height); 
         igh.width = Math.round(igh.height * f ); 
      }
      igh.src = ig.src;       
      return true; 
    } 
   return false; 
    
}

var imgloader = new Array(); 

function addimg(ig,wi,hi) {
   imgloader[imgloader.length] = {id:ig,w:wi,h:hi,status:0}; 
}

function imgloader_run() {
   var st = 0; 
   for(var i = 0; i < imgloader.length; i++) {
      var o = imgloader[i]; 
      if(o.status == 0) {
         if( setimg(document.getElementById(o.id),o.w,o.h) ) {
            imgloader[i].status = 1; 
         }  
      } 
   } 
   if(st == imgloader.length) {
      // window.clearInterval(imgloader_timer); 
   } 
}

var imgloader_timer = window.setInterval('imgloader_run()',250); 


/////////////////////////////////////////////////////////////////

var t_init = 0;
var t_htmlid = "tooltip";
var akt_vp_w = 0;

function ToolTipBewegen(evt) {
   if(document.all) {
      evt = window.event;
   }
   document.getElementById(t_htmlid).style.top = (evt.clientY + document.documentElement.scrollTop + 15) + "px";
   newleft = ((evt.clientX + 2) - 30);
   if (newleft + 340 <= akt_vp_w) {
      document.getElementById(t_htmlid).style.left = newleft + "px";
   }
}

function showTip(htmlid,inhalt,e){
   t_htmlid = htmlid;
   Init();
   document.getElementById(t_htmlid).innerHTML = inhalt;
   document.getElementById(t_htmlid).style.display="block";
}

function hideTip() {
   document.getElementById(t_htmlid).style.display="none";
}

function Init(e) {
   if (t_init == 0) {
      view = get_viewport();
      akt_vp_w = view[0];
      document.getElementById("toolcont").onmousemove = ToolTipBewegen;
      t_init = 1;
   }
}

/////////////////////////////////////////////////////////////////
var ea_boxes = new Array();

function show_hide_ea_box(htmlid,todo) {
   body1 = document.getElementsByTagName("body")[0];
   if (todo == 0 && document.getElementById(htmlid) == undefined) {
      bclassname = "ealert_box";
      if (arguments[3] != undefined) {
         bclassname = arguments[3]; 
      }
      div = document.createElement('div');
      div.className = bclassname;
      div.id = htmlid;
      remove_ea_boxes();
      ea_boxes.push(htmlid);

      div2 = document.createElement('div');
      div2.style.textAlign = "center"; 
      img = document.createElement('img');
      img.src = "http://images.immobilo.de/bilder/loading.gif";
      div2.appendChild(img);
      div.appendChild(div2);
      trz = "&";
      body1.appendChild(div);

      if (arguments[4]) {
         
         // div.style.marginLeft = '-' + (div.style.width % 2) + 'px';
         // div.style.marginTop = '-' + (div.height % 2) + 'px';
         
         // center popup 
         if (arguments[4]=='center'){
            nc('#'+htmlid).css('top', nc(window).height()/2-nc('#'+htmlid).height()/2);
            nc('#'+htmlid).css('left', nc(window).width()/2-nc('#'+htmlid).width()/2); 
         }else{
            var offset = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0;  
            var width =  nc("#show_eabox").width();
            div.style.marginLeft = '-' + Math.round(width / 2) + 'px';    
            div.style.marginTop = (offset - 150) + 'px';
            div.style.left = '50%';
            div.style.top  = '50%';
         }
         /*
         var left = document.getElementById("show_eabox").getBoundingClientRect().left;
         div.style.left = left+"px";
         */ 
         /*
         left = i_getLeft(document.getElementById("show_ea_box"));
         topw = i_getTop(document.getElementById("show_ea_box"));
         div.style.left = left+120+"px";
         div.style.top = topw+35+"px";
         */
         
      }
      else {
         view = get_viewport();
         right = parseInt(view[0]-((view[0]/2)+470));
         div.style.right = right+"px";
      }
      
      if (arguments[2]) {
         if (arguments[2].indexOf("?") == -1) {
             trz = "?"; 
         }
         ajax_call(show_hide_ea_box.arguments[2]+trz+"DIV="+htmlid); 
         jQuery('#ealert_box1').draggable({handle: '.eaheader', containment: 'document'});
         
      }     
   }
   else {
      if (document.getElementById(htmlid)) {
         body1.removeChild(document.getElementById(htmlid));
         jQuery('#ealert_box1').draggable('destroy');
      }
   }
}

function remove_ea_boxes() {
   if (ea_boxes.length > 0) {
      for (i = 0;i <= ea_boxes.length;i++) {
         if (document.getElementById(ea_boxes[i])){
            show_hide_ea_box(ea_boxes[i],1);
         }
      }
   }
}

var ea_errors = new Object();

function set_ea_errors(htmlid,txt,dow) {
   if (document.getElementById(htmlid)) {
      if (dow == 0) {
         document.getElementById(htmlid).style.border = "1px solid red";
         ea_errors[htmlid] = txt;
      }
      else {
         document.getElementById(htmlid).style.border = "1px solid #CCCCCC";
         ea_errors[htmlid] = ""; 
      }
   }
}

function write_ea_errors() {
   strw = "";
   for (var Eigenschaft in ea_errors) {
      if (ea_errors[Eigenschaft] != "") {
         strw += ea_errors[Eigenschaft];
         strw += "<br>";
      }
   }
   document.getElementById("reg_errors").innerHTML = strw;
   ea_errors = new Object(); //reset so that they will not be writen again
}

var mi_alr_set = 0;
function Show_mi_item(itemID) {
   var x = document.getElementById(itemID);
   if (mi_alr_set == 0) {
       x.style.left = (i_getLeft(document.getElementById("mi_link"))-100)+"px";
       mi_alr_set = 1;
   }
   if (x)
       x.style.display = "block";
   return true;
}

function Hide_mi_item(itemID) {
  var x = document.getElementById(itemID);
  if (x)
     x.style.display = "none";
  return true;
}

function confirm_ajax(script,txt) {
   Check = confirm(txt);
   if (Check) {
      ajax_call(script); 
      return true;
   }
   else {
      return false;
   }
}

function open_immoguide(anker) {
   if (document.getElementById('immogval')) {
      parent.location.href = "/stadt/"+document.getElementById('immogval').value+anker; // CHANGE: /wohnen/ 
   }
}

function flashFocus() {
   document.getElementById("txtSearch").focus()
   document.getElementById("txtSearch").select();
}

function position_map_info(htmlid) {
   if (document.getElementById(htmlid)) {
      // if opened in ireds, set margin to 0, to avoid overlapping
      if(typeof(window.ireds_MoveMenu) == "function") {
         document.getElementById(htmlid).style.marginTop = "0px";
      }
      //atop = i_getTop(document.getElementById("txtSearch")) + 30;
      //document.getElementById(htmlid).style.top = atop + "px";
      
      // remove these two lines, as they do not work anyway
      // aleft = i_getLeft(document.getElementById("txtSearch")) + 55;
      // document.getElementById(htmlid).style.left = aleft + "px";
   }
}
function change_send_button(){
   if(document.getElementById('suche_neu_starten')){
      document.getElementById('suche_neu_starten').style.backgroundImage = "url(http://images.immobilo.de/bilder/d1/suche_neu_starten_animated.gif)";
   }
   if(document.getElementById('suche_neu_starten2')){
      document.getElementById('suche_neu_starten2').style.backgroundImage = "url(http://images.immobilo.de/bilder/d1/suche_neu_starten_animated.gif)";
   }
}



function faq_menu_showhide(id,dow) {
   if (dow == 0) {
      document.getElementById("vater_"+id).style.display = "none";
      document.getElementById("ficon_"+id).src = "http://images.immobilo.de/bilder/plus.gif";
      document.getElementById("flink_"+id).onclick = function() { faq_menu_showhide(id,1); }  ;
   }
   else {
      document.getElementById("vater_"+id).style.display = "block";
      document.getElementById("ficon_"+id).src = "http://images.immobilo.de/bilder/minus.gif";
      document.getElementById("flink_"+id).onclick = function() { faq_menu_showhide(id,0);}  ;
   }
} 

/** 
 * email abo login form handler
 */

var emailabo_popup_form = {
      
   make_login: function () {
   
      nc('#eabox-title').html('Login');
      nc('#email_abo_form #popup-description').html('Bitte melden Sie sich an, damit die Suche zu Ihren Favoriten hinzugefügt werden kann.');
      nc('#email_abo_form input[name=LOGIN]').val('LOGIN');
      nc('#err_return').html('');
      nc('#password-field').show(); 
      nc('#popup-type-switcher').hide();

      return false;
   
   },
   
   make_register: function () {
   
      nc('#eabox-title').html('Suche per E-Mail abonnieren');
      nc('#email_abo_form #popup-description').html('Um weitere Angebote zu dieser Suche per Email zu erhalten, tragen Sie bitte Ihre Email-Adresse ein.');
      nc('#email_abo_form input[name=LOGIN]').val('EMAILABO');
      nc('#password-field').hide(); 
      nc('#popup-type-switcher').show();
      
      return false;
      
   },
   
   make_email_taken: function () {
      
      
      
   }
      
      
}

/** 
 * map highlighting
 */
function map_highlight() {
   // SOON
}

function map_no_highlight() {
   // SOON
}

/////////////////////////////////////////////////////////////////

// Check location//////

//returns true when location is serach
function is_search(){if(window.location.pathname.match("mieten") || window.location.pathname.match("kaufen") ||  window.location.pathname.match("liste")){return true;} else{return false;}}


//returns true when location is detail
function is_detail(){if(window.location.pathname.match("immobilien")){return true;} else{return false;}}

//returns true when location is immoguide
function is_immoguide(){if(window.location.pathname.match("stadt")){return true;} else{return false;}}
/////////////////////////////////////////

/**
 * marker with given key gets blue icon
 * 
 * @param key
 * @return void
 */
function pin_over(key){
   
   var iframe = helper_get_mapframe();
   
   if (typeof iframe === 'object' && iframe.markers && iframe.markers.length > 0) {
      
      for (var i = 0; i < iframe.markers.length; i++) {
         
         if (iframe.markers[i].KEY == key) {
            iframe.markers[i].setImage("http://images.immobilo.de/bilder/Pin_blue.png");
         }
         
      }
         
   }
   
}

/**
 * marker with given key gets red icon 
 * 
 * @param key
 * @return void
 */
function pin_out(key) {
   
   iframe = helper_get_mapframe();
   
   if (typeof iframe === 'object' && iframe.markers && iframe.markers.length > 0) {
         
      for (var i = 0; i < iframe.markers.length; i++) {
         
         if (iframe.markers[i].KEY == key) {
            iframe.markers[i].setImage("http://images.immobilo.de/bilder/Pin_red.png");
         }
         
      }
         
   }
   
}


function pinlisto() {
  var pl = {
   pins:new Array(), 
   generation: 0, 
   markers:false,
   addpoint:function (pio) {
        
      pio.GEN = this.generation; 
      var pid = pio.LAT+'-'+pio.LONG; 
      pid = pid.replace(/\./g,''); 
      var jj =  -1; 
      var ii = -1; 
      for(var i= 0; i < this.pins.length; i++) {
         if( this.pins[i].PID == pid) {
            ii = i; 
            for(var j = 0; j < this.pins[i].IDS.length; j++) {
               if(this.pins[i].IDS[j].ID == pio.ID) {
                  jj = j; 
               } 
            } 
         } 
      } 
      if(ii == -1) {
         ii = this.pins.length; 
         this.pins[ii] = {PID: pid, IDS: new Array(pio) }; 
         this.drawpin(ii); 
         
      } else {
         if(jj == -1) {
            jj= this.pins[ii].IDS.length; 
            this.pins[ii].IDS[jj] = pio; 
            this.addpin(ii,jj); 
         }
      } 

   }, 
   drawpin: function (iii) {
       log("drawpin"+iii+"-");
      var d = this.pins[iii] ; 
      var a = document.getElementById("storage"); 
      var html = '<div class="gmapoverl" style="background-color:#F3F5F7" id="gmapoverl'+d.PID+
         '" par=""><div style="float:left;color:#DB2A00"><strong>Angebote:</strong></div> '+
         '<div class="close"><img src="http://images.immobilo.de/bilder/iw_close.gif" onclick="top.lastfix = \'\'; document.getElementById(\'gmapoverl'+d.PID+'\').style.display= \'none\'"></div>' + 
         '<div class="clearer"></div><ul id="gmapoverul'+d.PID+'">'; 
      html = html + this.getHTML(d.IDS[0],true,d.PID); 
      html = html + "</ul></div>";
      a.innerHTML  = a.innerHTML+html; 
      
      gMapArray.ITEMS.push({'LAT':d.IDS[0].LAT,'LONG':d.IDS[0].LONG,'TXT':'','KEY':d.PID});
      
   },
   getHTML: function (poi,xtra,did) {
	   var link = '/immobilien/'+poi.ID;
      if (poi.OLINK && poi.OLINK!="") link = poi.OLINK;
      
      var html = '<li id="GIP'+poi.ID+'"><b>&middot;</b> <a href="'+link+'" target="_top" onmouseover="rahmen(\'fitem'+poi.ID+'\',1)" '+ // CHANGE: /wohnen/ 
         ' onmouseout="rahmen(\'fitem'+poi.ID+'\',0)" onclick="top.location.href=\''+link+'\'" title="'+poi.TXT+'">'+poi.TXT+'</a></li>';
      // show details for object
      if (xtra){
         html+= '<div id="det'+did+'" class="poidetail">';
         if (poi.THMB!='') html+= '<img class="img" src="'+poi.THMB+'" border="0">';
         html+= '<span class="txt"><strong>'+poi.PRC+' &euro;</strong>';
         if (poi.WAS!='') html+= '/ '+poi.WAS
         html+= '<br />'+poi.RMS+' Zimmer, '+poi.SQM+' m&sup2;<br /><br /></span>';
         html+= '<a class="more" href="'+link+'">mehr...</a></div>';
      }
      return html; 
   },
   addpin: function(iii,jjj) {
      var poi = this.pins[iii].IDS[jjj]; 
         log("add pin:"+iii+" p:"+jjj); 
      var h = this.getHTML(poi); 
      if(document.getElementById("gmapoverul"+this.pins[iii].PID)) {
         document.getElementById("gmapoverul"+this.pins[iii].PID).innerHTML+= h;
      } 
      // hide details for objects because list includes more than one object
      if (document.getElementById("det"+this.pins[iii].PID)){
         document.getElementById("det"+this.pins[iii].PID).style.display="none";
      } 
   } ,
   addPoiPoint:function (pio) {
      pio.GEN = this.generation; 
      var pid = pio.LAT+'-'+pio.LONG+'-'+pio.POITYPE; 
      pid = pid.replace(/\./g,''); 
      var jj =  -1; 
      var ii = -1; 
      for(var i= 0; i < this.pins.length; i++) {
         if( this.pins[i].PID == pid) {
            ii = i; 
            for(var j = 0; j < this.pins[i].IDS.length; j++) {
               if(this.pins[i].IDS[j].ID == pio.ID) {
                  jj = j; 
               } 
            } 
         } 
      } 
      if(ii == -1) {
         ii = this.pins.length;
         this.pins[ii] = {PID: pid, IDS: new Array(pio), POITYPE: pio.POITYPE, TYPETXT: pio.TYPETXT }; 
         this.drawPoiPin(ii); 
         
      } else {
         if(jj == -1) {
            jj= this.pins[ii].IDS.length; 
            this.pins[ii].IDS[jj] = pio; 
            this.addPoiPin(ii,jj); 
         }
      } 

   }, 
   drawPoiPin: function (iii) {
       log("drawpin"+iii+"-");
      var d = this.pins[iii] ; 
      var a = document.getElementById("storage"); 
      
      var html = '<div class="gmapoverl" style="background-color:#F3F5F7" id="gmapoverl'+d.PID+
         '" par=""><div style="float:left;color:#DB2A00"><strong>'+d.TYPETXT+':</strong></div> '+
         '<div class="clearer"></div><ul id="gmapoverul'+d.PID+'">'; 
      html = html + this.getPoiHTML(d.IDS[0]); 
      html = html + "</ul></div>";
      a.innerHTML  = a.innerHTML+html; 
      gMapArray.ITEMS.push({'LAT':d.IDS[0].LAT,'LONG':d.IDS[0].LONG,'TXT':'','KEY':d.PID, 'POITYPE':d.POITYPE});
      
   },
   getPoiHTML: function (poi) {
      var html = '<li id="GIP'+poi.ID+'"><b>&middot;</b> '+poi.TXT+''; 
      for (i=0; i<poi.LOGOS.length; i++){
         html+=' <img src="'+poi.LOGOS[i]+'" style="margin-right:2px;">';
      }
      return html; 
   },
   addPoiPin: function(iii,jjj) {
      var poi = this.pins[iii].IDS[jjj]; 
         log("add pin:"+iii+" p:"+jjj); 
      var h = this.getPoiHTML(poi); 
      if(document.getElementById("gmapoverul"+this.pins[iii].PID)) {
         document.getElementById("gmapoverul"+this.pins[iii].PID).innerHTML = 
         document.getElementById("gmapoverul"+this.pins[iii].PID).innerHTML + h; 
      } 
   } ,
   updateGen: function(clear)  {

      // slider changes will clear previous results
      if (clear && clear === 1) {
         mapmarkers_reduce(0);
      }
      else if (clear === 0) {
         // map dragged
         
         max = 30;
         m = window.frames['map_iframe'].map;
         z = window.frames['map_iframe'].markers || [];
         p = this.pins;
         
         while (p.length > 30) {
            
            var pin = p.shift();
            var pid = gMapArray.ITEMS.shift();
            
            // first, remove any markers sharing same geoposition
            for (var k = 0; k < z.length; k++) {

                z_key = new String(z[k].getLatLng().lat() + '-' + z[k].getLatLng().lng()).replace(/\./g, '');

                if (pin.PID == z_key) {
                  m.removeOverlay(z[k]);
                }

            }
            
            // delete container from "storage"
            nc('#storage').find('#gmapoverl' + pin.PID).remove();
               
            
         }
         
      }
      
      /*
      this.generation++; 
      if(this.generation -3 >= 0) {
         if(!this.markers) {
            this.markers =document.getElementById('map_iframe').contentWindow.markers; 
         }
         var g = this.generation -3; 
         for(var i= 0; i < this.pins.length; i++) {
            var gensum = 0; 
            for(var j = 0; j < this.pins[i].IDS.length; j++) {
               if(this.pins[i].IDS[j].GEN <= g) {
                   log("del pin:"+i+" pos:"+j)
                   if(document.getElementById("GIP"+this.pins[i].IDS[j].PID) ) {
                  document.getElementById("GIP"+this.pins[i].IDS[j].PID).style.display = 'none'; 
                   }
                   this.pins[i].IDS[j].GEN  = 0; 
               }
               gensum += this.pins[i].IDS[j].GEN; 
               log("del pin:"+i+" SUM:"+gensum);
               if(gensum == 0) {
                 // log("L:"+m.markers.length+"-"+this.pins[i].PID); 
                 for(var mi= 0; mi < this.markers.length; mi++) {
                   if(this.markers[mi].KEY == this.pins[i].PID) {
                     log("HIDE PIN"+mi); 
                     this.markers[mi].hide(); 
                   }
                 }
               }
            }
         }
      } 
      log("<hr>"); 
      */
   } 
  } 
  return pl; 
} 

var pinlist = new pinlisto(); 

index_data=new Array();
index_data_key=new Array();

// <!-- IndexTools Customization Code -->
function in_array(item,arr) {
for(p=0;p<arr.length;p++) if (item == arr[p]) return true;
return false;
}
function make_index_ajax(name,value) {
  switch (name) {
    case "PTO": 
          index_data['preis_max']=value;
          break;
   case "PFROM": 
          index_data['preis_min']=value;
          break;
    case "SFROM": 
          index_data['grosse_min']=value;
          break;
    case "STO": 
          index_data['grosse_max']=value;
          break;
    case "RADIUS": 
          index_data['RADIUS']=value;
          break;
    case "RTO": 
          index_data['zimmer_max']=value;
          break;
    case "RFROM": 
          index_data['zimmer_min']=value;
          break;
 
          
          
            }
}


function makeindextool(group,name,action){
if (name=="select"){
index_data_key=new Array("preis_min","preis_max","art","typ","zimmer","grosse_min","grosse_max","treffer","wo","radius");
index_data['zimmer']=document.BOXFORM.RFROM.value;
index_data['art']=document.BOXFORM.WAS.value;
index_data['typ']=document.BOXFORM.TYP.value;
name="";
}
if (action=="01"){
index_data['anbieter']=index_data['outklick_url'].slice(index_data['outklick_url'].indexOf("http://www.")+11,-1);
if(index_data['anbieter'].indexOf("?") !=-1){index_data['anbieter']=index_data['anbieter'].slice(0,index_data['anbieter'].indexOf("?"));}
if(index_data['anbieter'].indexOf("/") !=-1){index_data['anbieter']=index_data['anbieter'].slice(0,index_data['anbieter'].indexOf("/"));}
index_data_key=new Array("amounts","anbieter");
index_data['amounts']='USD0.70';

}

sortier_help=new Array('','aktuellste Angebote zuerst','Entfernung aufsteigend','Entfernung absteigend','geringster Preis','höchster Preis','kleinste Fläche','größte Fläche');
if(group=="Suche Sortierung"){
if(name=='a'){
index_data['sortiere']=sortier_help[document.sort_form.a.value];
}
if(name=='b'){
index_data['sortiere']=sortier_help[document.sort_form2.b.value];
}
name="";
index_data_key=new Array('sortiere');
}
if(group=='Suche > Expose > Details mehr'){
index_data_key=new Array("expose");
}
if(group=='Suche > Expose > Details weniger'){
index_data_key=new Array("expose");
}

if(action=='03'){ // <!-- weiterempfehlen -->
index_data_key=new Array("expose");
}
if(action=='04'){ // <!-- weiterempfehlen abgeschickt-->
index_data_key=new Array("expose");
}
if(group=="Suche Pageinator"){

index_data['page_from']=name;
index_data['page_to']=action;
name="";
action="";
index_data_key=new Array('page_from','page_to');
}

if(index_data['RADIUS']>0){
index_data_key.push("RADIUS");
}

var tracking_object = createITT();
tracking_object.ACTION=action;
tracking_object.DOCUMENTGROUP=group;
tracking_object.DOCUMENTNAME=name;


ausgabe="Indextool gestartet, Gruppe: '"+group+ "' Name: '"+name+"' Action: '"+action+"'! \n \n Eigenschaften: \n\n";
if(typeof(index_data['preis_min'])!='undefined' && in_array("preis_min",index_data_key)){
tracking_object._s_cf01=index_data['preis_min'];
ausgabe+="Preis Min: "+index_data['preis_min']+"\n";}  
if(typeof(index_data['preis_max'])!='undefined' && in_array("preis_max",index_data_key)){
tracking_object._s_cf02=index_data['preis_max'];
ausgabe+="Preis Max: "+index_data['preis_max']+"\n";}
if(typeof(index_data['art'])!='undefined' && in_array("art",index_data_key)){
tracking_object._s_cf03=index_data['art'];
ausgabe+="Art: "+index_data['art']+"\n";}
if(typeof(index_data['typ'])!='undefined' && in_array("typ",index_data_key)){
tracking_object._s_cf04=index_data['typ'];
ausgabe+="Typ: "+index_data['typ']+"\n";}
if(typeof(index_data['zimmer'])!='undefined' && in_array("zimmer",index_data_key)){
tracking_object._s_cf05=index_data['zimmer'];
ausgabe+="Zimmer: "+index_data['zimmer']+"\n";}
if(typeof(index_data['grosse_min'])!='undefined' && in_array("grosse_min",index_data_key)){
tracking_object._s_cf06=index_data['grosse_min'];
ausgabe+="Grosse Min: "+index_data['grosse_min']+"\n";}
if(typeof(index_data['grosse_max'])!='undefined' && in_array("grosse_max",index_data_key)){
tracking_object._s_cf07=index_data['grosse_max'];
ausgabe+="Grosse Max: "+index_data['grosse_max']+"\n";}
if(typeof(index_data['expose'])!='undefined' && in_array("expose",index_data_key)){
tracking_object._S_SKU=index_data['expose'];
ausgabe+="Expose: "+index_data['expose']+"\n";}
if(typeof(index_data['wo'])!='undefined' && in_array("wo",index_data_key)){
tracking_object._S_ISK=index_data['wo'];
ausgabe+="Wo: "+index_data['wo']+"\n";}
if(typeof(index_data['treffer'])!='undefined' && in_array("treffer",index_data_key)){
tracking_object._S_ISR=index_data['treffer'];
ausgabe+="Treffer: "+index_data['treffer']+"\n";}
if(typeof(index_data['sortiere'])!='undefined' && in_array("sortiere",index_data_key)){
tracking_object._s_cf12=index_data['sortiere'];
ausgabe+="Sortierung: "+index_data['sortiere']+"\n";}
if(typeof(index_data['immoguide_ort'])!='undefined' && in_array("immoguide_ort",index_data_key)){
tracking_object._S_ISK=index_data['immoguide_ort'];
ausgabe+="Ort: "+index_data['immoguide_ort']+"\n";}
if(typeof(index_data['page_from'])!='undefined' && in_array("page_from",index_data_key)){
tracking_object._s_cf10=index_data['page_from'];
ausgabe+="Herkunftsseite: "+index_data['page_from']+"\n";}
if(typeof(index_data['page_to'])!='undefined' && in_array("page_to",index_data_key)){
tracking_object._s_cf11=index_data['page_to'];
ausgabe+="Zielseite: "+index_data['page_to']+"\n";}
if(typeof(index_data['anbieter'])!='undefined' && in_array("anbieter",index_data_key)){
tracking_object._s_cf09=index_data['anbieter'];
ausgabe+="Anbieter: "+index_data['anbieter']+"\n";}
if(typeof(index_data['amounts'])!='undefined' && in_array("amounts",index_data_key)){
tracking_object._S_AMOUNTS=index_data['amounts'];
tracking_object.AMOUNT=index_data['amounts'];
ausgabe+="Einnahmen: "+index_data['amounts']+"\n";
}
if(typeof(index_data['RADIUS'])!='undefined' && in_array("RADIUS",index_data_key)){
tracking_object._s_cf08=index_data['RADIUS'];
ausgabe+="RADIUS: "+index_data['RADIUS']+"\n";
}





// <!-- alert(ausgabe); -->
tracking_object.submit();


}

function forceStreetSearch(){
   var str = document.getElementById('txtSearch').value
   // if query has a length of 5 and suggest-box is not shown (no results)
   if (str.length>5){
      document.getElementById("STRS").value=0;
   }else{
      document.getElementById("STRS").value=1;
   }
   switchStreetSearch(true);
}

function switchStreetSearch(quiet){
   var strs=document.getElementById("STRS");
   var btn=document.getElementById("strsbtn");
   if (strsForced){
      strs.value=0;
      strsForced=false;
   }
   if(parseInt(strs.value)==1){
      btn.style.opacity='0.5';
      btn.style.filter='alpha(opacity=50)';
      strs.value=0;
      if (!quiet) {     	  
    	  document.getElementById("txtSearch").value = (nc('body').hasClass('studivz') ? 'Gib Deine Wunsch-Stadt oder PLZ an.' : 'Geben Sie Ihre Stadt, PLZ oder Straße ein.');
      }
      document.getElementById("strsbtn").title='Aktivieren Sie hier die Straßensuche';
      document.getElementById("strsbtn").title='Aktivieren Sie hier die Straßensuche';
      document.getElementById("helpdiv").innerHTML = '';
   }else{
      btn.style.opacity='1';
      btn.style.filter='alpha(opacity=100)';
      strs.value=1;
      if (!quiet) document.getElementById("txtSearch").value='Geben Sie Ihren Straßennamen und Ort ein.';
      document.getElementById("strsbtn").title='Deaktivieren Sie hier die Straßensuche';
      document.getElementById("strsbtn").title='Deaktivieren Sie hier die Straßensuche';
      document.getElementById("helpdiv").innerHTML = 'z.B. "Friedrichstr. Berlin" oder "Leopoldstrasse München"';
   }
   var $strstt = jQuery.noConflict();
   $strstt(document).ready(function() {
        $strstt('#strsbtn').tooltip({showURL: false, track: true, extraClass: "autowidth"});
   });

   if (!quiet){
      self.focus(); 
      document.FM.WO.focus(); 
      document.FM.WO.select();
   }
}

function createRSSLink(rsslink){
   var link = document.getElementById("rsshlink");
   if (link){
      link.href = rsslink;
   }else{
      var head = document.getElementsByTagName('head').item(0);
      var link = document.createElement("link");
      link.setAttribute("rel", "alternate");
      link.setAttribute("type", "application/rss+xml");
      link.setAttribute("title", "Suche als RSS-Feed");
      link.setAttribute("id", "rsshlink");
      link.setAttribute("href", rsslink);
      head.appendChild(link);
   }
}

function switchBanners(openx){
   if (nc("#left_ad_box")){
      //code = "<iframe id='3780d8d' name='3780d8d' src='http://opendix.immobilo.de/www/delivery/avw.php?zoneid=14&amp;n=3780d8d' framespacing='0' frameborder='no' scrolling='no' width='160' height='600'><a target='_blank' rel='nofollow' href='http://opendix.immobilo.de/www/delivery/ck.php?n=3780d8d'><img border='0' alt='' src='http://opendix.immobilo.de/www/delivery/avw.php?zoneid=14&amp;n=3780d8d' /></a></iframe>";
      code = "<iframe id='a0ac413a' name='a0ac413a' src='http://opendix.immobilo.de/www/delivery/afr.php?zoneid=14&amp;cb=92489802348"+openx+"' framespacing='0' frameborder='no' scrolling='no' width='160' height='600'><a rel='nofollow' href='http://opendix.immobilo.de/www/delivery/ck.php?n=ac611602&amp;cb=92489802348' target='_blank'><img src='http://opendix.immobilo.de/www/delivery/avw.php?zoneid=14&amp;cb=92489802348&amp;n=ac611602' border='0' alt='' /></a></iframe>";
      nc("#left_ad_box").empty().html(code);
   }
   if (nc("#right_ad_box")){
      //code = "<iframe id='415af32' name='415af32' src='http://opendix.immobilo.de/www/delivery/avw.php?zoneid=15&amp;n=415af32' framespacing='0' frameborder='no' scrolling='no' width='300' height='250'><a target='_blank' rel='nofollow' href='http://opendix.immobilo.de/www/delivery/ck.php?n=415af32'><img border='0' alt='' src='http://opendix.immobilo.de/www/delivery/avw.php?zoneid=15&amp;n=415af32' /></a></iframe>";
      code = "<iframe id='a1603eb8' name='a1603eb8' src='http://opendix.immobilo.de/www/delivery/afr.php?zoneid=15&amp;cb=349437340"+openx+"' framespacing='0' frameborder='no' scrolling='no' width='300' height='250'><a rel='nofollow' href='http://opendix.immobilo.de/www/delivery/ck.php?n=a2dd5f2f&amp;cb=349437340' target='_blank'><img src='http://opendix.immobilo.de/www/delivery/avw.php?zoneid=15&amp;cb=349437340&amp;n=a2dd5f2f' border='0' alt='' /></a></iframe>";
      nc("#right_ad_box").empty().html(code);
   }
}

//HSF-337 resize breadcrumb font if linebreak
function resizeBreadcrumb(){
   if (nc('#Ergebnis')){
      nc('#Ergebnis').css({'font-size':'13px'});
      if(nc('#Ergebnis').height()>25){
         nc('#Ergebnis').css({'font-size':'11px'});
      }
   }
}



function toggleMapIFrame(large){
   mapFrame = helper_get_mapframe();
   if (typeof mapFrame.toggleMap == 'function'){
      mapFrame.toggleMap(large);
   }
}
/**
 * enlarges or minimizes google map iframe
 * @param state string containing either 'small' or 'large' 
 * @return boolean always returns false
 */
function toggleMapSize (state) {
   
   // determine which state ... 
   if (state == 'small') {
   
	   
	   
      nc('#ad_top_space').css('height', '10px');
      nc('#Main').removeClass('extractedMap');
      if (!is_search()) {
         nc('#spalte3').removeClass('expandedMap');
      }
      
      // shorten animation time, as it would lead to race-conditions otherwise
      if (!is_search() && window.frames['map_iframe'].poi_selector_animation_has_run ) {
         nc('#map_iframe').animate({'height': 341 + window.frames['map_iframe'].$('#poi_selector').height() + 'px'}, 250);
      }
      else {
         nc('#map_iframe').css('height', '335px');
      }
      
      somefunkyvar = helper_get_mapframe();
      centerpoint = somefunkyvar.map.getCenter();
      somefunkyvar.map.checkResize();
      somefunkyvar.gmapzoom = true;
      if (somefunkyvar.is_detail && somefunkyvar.detailviewcenterpoint) {
         somefunkyvar.map.setCenter(somefunkyvar.detailviewcenterpoint);
      }
      else {
         somefunkyvar.map.setCenter(centerpoint);
      }
      
      get_map_pos();
      
      // dynamic_bookmark_set('Karte_klein');
      somefunkyvar.gmapzoom = false;
      
      nc.get('?stdview=t&cview=t');
   }
   else if (state == 'large') {
	   
      nc('#ad_top_space').css('height', '33px');
      // msie loses width info on map resize (large) because of missing wrapper around iframe in detailview 
      if (nc.browser.msie && nc.browser.version <= 7.0) {
         nc('#spalte2 div.Sortieren').css('width', '415px');
      }
      
      nc('#Main').addClass('extractedMap');
      if (!is_search()) {
         nc('#spalte3').addClass('expandedMap');
      }
      
      nc('#map_iframe').css('height', '400px');
      
      somefunkyvar = helper_get_mapframe();
      centerpoint = somefunkyvar.map.getCenter();
      somefunkyvar.map.checkResize();
      somefunkyvar.gmapzoom = true;
      if (somefunkyvar.is_detail && somefunkyvar.detailviewcenterpoint) {
         
         somefunkyvar.map.setCenter(somefunkyvar.detailviewcenterpoint);
      }
      else {
         somefunkyvar.map.setCenter(centerpoint);
      }
         
      get_map_pos();
      
      // dynamic_bookmark_set('Karte_gross');
      somefunkyvar.gmapzoom = false;
      
      nc.get('?mapview=t&cview=t');
   }
   
   return false;
   
}

/** 
 * toggles "updating search results" indicator
 * 
 * creates a new div-container for displaying indicator
 * destroys div-container after search list has been updated 
 * 
 * @param param
 *  object literal, should at least contain boolean property 'show'
 *
 * @return void
 */
function mapResizeLoadingAnimation(param) {
   
   if (typeof param === 'object' && is_search()) {
      
	   if (param.show) {
		   
		   if (nc('#Main').hasClass('extractedMap')) {
			   window.frames['map_iframe'].map.disableDragging();
			   nc('.map_wrapper').append('<div id="updateOnMapDrag">Angebote werden aktualisiert</div>');
		   }
	       
	       // applies only to msie up to version 7
	       if (nc.browser.msie && nc.browser.version < 8.0) {
	    	   nc('#updateOnMapDrag').css({marginLeft: '-720px'});
	       }
	   
	   }
	   else {
		   nc('#updateOnMapDrag').remove();
	       window.frames['map_iframe'].map.enableDragging();
	   }
	   
   }
   
}

nc(document).ready(function() {
   
	resizeBreadcrumb();
   
   // HSF-727 kill hardcoded eventhandler
	var autocompleteElement = document.getElementById('txtSearch');
	if (autocompleteElement.nodeType) {
		searchSuggestHandler.oField = autocompleteElement;
		autocompleteElement.onkeyup = searchSuggestNG;
		autocompleteElement.onclick = searchSuggestHandler.clearSuggest;
	}

   // HSF-22
   if (nc('body.frontpage').length == 1) {
      nc.get('/dynamic/frontpage_recentsearches', {}, function(data, textStatus) {
         if (textStatus == 'success' && data.status == '__success__') {

            elt = nc('body.frontpage div.Spy-Start.Second div.Right.type-content');
            nc('h2', elt).text((nc('body').hasClass('studivz') ? 'Deine letzten Suchen' : data.headline));
            nc('div.scroll_content', elt).html('<div id="recent-searches">' + data.content + '</div>');

            // prevent scrolling if there is nothing to scroll
            if (nc('#recent-searches').height() <= 170) {
               nc('a[href=#]', elt).remove();
            }
      
         }
      }, 'json');
      
      // load frontpage formhelper 
      nc.get('/dynamic/frontpage_formhelper', {}, function(data, textStatus) {
         if (textStatus == 'success' && data.status == '__success__') {
            form = nc('form#FM');
            dummy = {0: 'ALL', 1: 'HAUS', 2: 'WOHNUNG', 3: 'WG', 4: 'GEWERBE', 5: 'GRUNDSTUECK'};
            nc.each(data.content, function (key, value) {
               
               if (key == 'RFROM' || key == 'RTO' || key == 'WAS') {
                  nc('#' + key + '_ option[@value=' + value + ']', form).attr('selected', 'selected');
               }
               else if (key == 'TYP') {
                  nc('#' + key + '_' + value, form).attr('selected', 'selected');
               }
               else {
                  nc("#" + key, form).val(value);
               }
            });
            }
         }, 'json');   
      
   }
   
   // add autocomplete attributes dynamically
   nc('input.autocomplete').attr('autocomplete', 'off');

   nc('#immosearchmenu').click(function () { return showMenu('SubNav-Search'); });
   nc('#immoguidemenu').click(function () { return showMenu('SubNav-Guide'); });
   nc('#immopartnermenu').click(function () { return showMenu('SubNav-Partner'); });
   
   // set top position of subnav according to dummy
   if (nc("#SubNav-Dummy").length > 0) {
      nc("#SubNav-Dummy").show();// has to visible first, otherwise jquery will throw an exeception
      nc("#SubNav-Balken").css('top',nc("#SubNav-Dummy").position().top);
      nc("#SubNav-Dummy").hide();
   }
   
   // HSF-567 attach dialog
   // TODO: calculate offset from right;
   nc('#expose-compare-popup').dialog({
   	   autoOpen: false,
   	   bgiframe: true,
   	   buttons: {},
   	   closeOnEscape: true,
   	   dialogClass: '',
   	   modal: false,
   	   resizable: false,
   	   draggable: true,
   	   width: 240,
   	   height: 300,
   	   // position: ['right', 'center'],
   	   position: [(nc('#Main').offset().left + nc('#Main').width() - 240), 'center'],
   	   title: 'Vergleichen'
   	});
   
   // HSF-472 log leads, pseudo-mask real link target
   nc('.new-window-link').bind('click', function(e) {
	   if (typeof Open === 'function') {
	     Open(nc(this).attr('href'), '');
	   }
	   else {
	     var leadwindow = window.open(nc(this).attr('href'), '_blank', "width=950,height=700,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes"); 
	   }
	   return false;
   });
   
});

lastmnu=null;
function showMenu(subNavID,newmnu) {
   var links = [];
   links['SubNav-Partner'] = 'link_immopartner';
   links['SubNav-Guide'] = 'link_immoguide';
   links['SubNav-Search'] = 'link_immosearch';
   
   if (lastmnu==subNavID) lastmnu=null;
   else if (lastmnu!=null) showMenu(lastmnu,subNavID);
   
   if (document.getElementById(subNavID)){
      func=null;
      if (nc('#'+subNavID).css('display')=='none'){
         nc('#SubNav-Balken, #SubNav-Dummy, #'+subNavID).slideDown('slow',function (){
            if (subNavID=='SubNav-Partner') nc('#SubNav-Partner').css('z-index',2);
            if (subNavID=='SubNav-Guide') nc('#SubNav-Guide').css('z-index',2);
            if (subNavID=='SubNav-Search') nc('#SubNav-Search').css('z-index',2);
            
            if (subNavID!='SubNav-Partner') nc('#').css('z-index',1);
            if (subNavID!='SubNav-Guide') nc('#SubNav-Guide').css('z-index',1);
            if (subNavID!='SubNav-Search') nc('#SubNav-Search').css('z-index',1);
         });
         document.getElementById(links[subNavID]).className='hoverbtn';
         lastmnu=subNavID;
      }else{
         nc('#SubNav-Balken, #SubNav-Dummy, #'+subNavID).slideUp('slow');
         document.getElementById(links[subNavID]).className='';
         lastmnu=null;
      }
      return false;
   }else{
      return true;
   }
}
function hover_immo_menu(id,id2,hover){
   var el =document.getElementById(id);
   if (el){
      if (hover){
         el.className = 'hoverbtn';
      }else{
         if (nc('#'+id2).css('display')=='none'){
            el.className = '';
         }
      }
   }
}
function hover_immo_sub(id,hover){
   var el =document.getElementById("subNav_"+id);
   if (el){
      if (hover){
         el.style.backgroundImage = "url(http://images.immobilo.de/bilder/d1/bgPartnerNavBut.gif)";
         show_subNavLvl2(id,true);
      }else{
         el.style.backgroundImage = "";
         show_subNavLvl2(id,false);
      }
   }
}
function show_subNavLvl2(id,show){
   
   var el = nc("#subNavLvl2_"+id);
   var left = nc("#subNav_"+id).position().left;
   var top = nc("#subNav_"+id).height()+1;
   
   // internet explorer and box-model ...
   if (nc.browser.msie) {
      left += 2;
   }
   
   if (el) {
      if (show) {
         el.css({
            left: left,
            top: top,
            display: 'block'
         });
      } else {
         el.css('display', 'none');
      }
   }
}

function trackSBox(el,str){
   nc.get(str+"&ts="+(Math.round(new Date().getTime()/1000)),function(data){
      window.location.href = el.href;
   });
   return false;
}
function changeView(viewtype){
   nc.get(window.location.pathname+'?' + viewtype + '=t&cview=t', function (){
      window.location.reload( false );
   });
}

function select_marketing_type(mtyp,event){
   if(window.event) {
      evt = window.event; 
      Tastencode = evt.keyCode;
   } else {
      if(event) {
         Tastencode = event.which; 
      }
   }
   if(Tastencode==37 || Tastencode==39){ // left, right
      var max_type=2;
      var cur_type=-1;
      
      if (document.FM.WAS.value=='MIETE'){
         cur_type=0;
      }else if (document.FM.WAS.value=='KAUF'){
         cur_type=1;
      }else if (document.FM.WAS.value=='HAUSBAU'){
         cur_type=2;
      }
      
      if (Tastencode==37 && cur_type==0) cur_type=max_type;
      else if (Tastencode==37) cur_type--;
      else if (Tastencode==39 && cur_type==max_type) cur_type=0;
      else if (Tastencode==39) cur_type++;
      
      if (cur_type>=0) switch_marketing_type(cur_type,true);
   }else if(Tastencode==13){ // enter
      if (document.FM.WAS.value!=mtyp){
         if (mtyp=='MIETE'){
            switch_marketing_type(0,true);
         }else if (mtyp=='KAUF'){
            switch_marketing_type(1,true);
         }else if (mtyp=='HAUSBAU'){
            switch_marketing_type(2,true);
         }
      }
   }
   return false;
}

function switch_marketing_type(mtyp,nofocus,typ_select){
   if (mtyp==1){
      classToAdd = 'kaufen';

      nc('#pin_map_cont').show();
      nc('#bland_map_cont').hide();
      
      nc('#StartSuche .preis-spanne').show();
      nc('#StartSuche .zimmer').show();
      nc('#StartSuche .groesse').show();
      
      nc('#StartSuche .hausbau-preis-spanne').hide();
      nc('#StartSuche .neubau-bezugsfertig').hide();
      nc('#StartSuche .neubau-preis-kategorie').hide();
      nc('#StartSuche .neubau-preis-spanne').hide();
      
      document.FM.WAS.value='KAUF';
      
      dummy = {'ALL':'alle', 'HAUS':'Haus', 'WOHNUNG':'Wohnung', 'GEWERBE':'Gewerbe'};
      
      if (nc('#txtSearch').val() == 'Geben Sie Ihr Bundesland ein.') {
    	  nc('#txtSearch').val((nc('body').hasClass('studivz') ? 'Gib Deine Wunsch-Stadt oder PLZ an.' : 'Geben Sie Ihre Stadt, PLZ oder Straße ein.'));
      }
       
      if (document.getElementById('selectbtn')) {
         var div2 = document.getElementById('selectbtn');
         div.removeChild(div2);
      }
   }else if (mtyp==2){
      classToAdd = 'hausbau';
      
      nc('#pin_map_cont').show();
      nc('#bland_map_cont').show();
      
      nc('#StartSuche .preis-spanne').hide();
      nc('#StartSuche .zimmer').hide();
      nc('#StartSuche .groesse').hide();
      nc('#StartSuche .neubau-bezugsfertig').hide();
      nc('#StartSuche .neubau-preis-kategorie').hide();
      nc('#StartSuche .neubau-preis-spanne').hide();
      
      nc('#StartSuche .hausbau-preis-spanne').show();
      
      document.FM.WAS.value='HAUSBAU';
      
      dummy = hausbau_typen;
      
      nc('#txtSearch').val('Geben Sie Ihr Bundesland ein.');
      
      div = document.getElementById("sucheText");
      div2 = document.createElement('div');
      div2.id = "selectbtn";
      div2.onclick = function (){ hbselectbtn_pressed(); };
      div.appendChild(div2);
   }else if (mtyp==3){
      classToAdd = 'neubau';
      
      nc('#pin_map_cont').show();
      nc('#bland_map_cont').hide();
      
      nc('#StartSuche .preis-spanne').hide();
      nc('#StartSuche .zimmer').hide();
      nc('#StartSuche .groesse').hide();
      nc('#StartSuche .hausbau-preis-spanne').hide();
      
      nc('#StartSuche .neubau-bezugsfertig').show();
      nc('#StartSuche .neubau-preis-kategorie').show();
      nc('#StartSuche .neubau-preis-spanne').show();
      
      document.FM.WAS.value='NEUBAU';
      
      dummy = neubau_typen;
      
      if (nc('#txtSearch').val() == 'Geben Sie Ihr Bundesland ein.')
         nc('#txtSearch').val('Geben Sie Ihre Stadt, PLZ oder Straße ein.');
      
      if (document.getElementById('selectbtn')) {
         var div2 = document.getElementById('selectbtn');
         div.removeChild(div2);
      }
   }else{
      classToAdd = 'mieten';

      nc('#pin_map_cont').show();
      nc('#bland_map_cont').hide();
      
      nc('#StartSuche .preis-spanne').show();
      nc('#StartSuche .zimmer').show();
      nc('#StartSuche .groesse').show();
      
      nc('#StartSuche .hausbau-preis-spanne').hide();
      nc('#StartSuche .neubau-bezugsfertig').hide();
      nc('#StartSuche .neubau-preis-kategorie').hide();
      nc('#StartSuche .neubau-preis-spanne').hide();
      
      document.FM.WAS.value='MIETE';
      
      dummy = {'ALL':'alle', 'HAUS':'Haus', 'WOHNUNG':'Wohnung', 'WG':'WG', 'GEWERBE':'Gewerbe'};
      
      
      if (nc('#txtSearch').val() == 'Geben Sie Ihr Bundesland ein.')
         nc('#txtSearch').val('Geben Sie Ihre Stadt, PLZ oder Straße ein.');
      
      if (document.getElementById('selectbtn')) {
         var div2 = document.getElementById('selectbtn');
         div.removeChild(div2);
      }
   }
   
   nc('#sucheText').removeClass('mieten kaufen hausbau neubau').addClass(classToAdd);
   nc('#typ_select').removeClass('mieten kaufen hausbau neubau').addClass(classToAdd);
   
   switch (mtyp) {
    case 2: // hausbau
   	case 3: // neubau
   		var numMap = ((typeof typ_select !== 'undefined') && (!isNaN(typ_select)) ? typ_select : null );
	    break;
	default:
		if ((typeof typ_select !== 'undefined') && (!isNaN(typ_select))) {
			mappings = ['ALL', 'HAUS', 'WOHNUNG' , 'WG', 'GEWERBE'];
			var numMap = (mappings[typ_select] != document.FM.TYP.value) ? document.FM.TYP.value : mappings[typ_select];
		}
   }
   
   var bck = numMap || document.FM.TYP.value || nc("#TYP option:selected").val() || 'ALL';
   document.FM.TYP.innerHTML = '';
   nc.each(dummy, function (key, value) {
	   sel = (bck == key) ? 'selected="selected"' : '';
	   // msie breaks if using innerHTML
	   nc('#TYP').append('<option id="TYP_'+key+'" value="'+key+'" '+sel+'>'+value+'</option>');
   });
   
   nc('#TYP').trigger('dataChanged');
   
   if (!nofocus){
      document.getElementById("txtSearch").focus()
      document.getElementById("txtSearch").select();
   }
}

function hbselectbtn_pressed(){
   if(document.getElementById('search_suggest_rahmen').style.display != "none" 
      && nc('#suggest_table') && nc('#suggest_table tr').length>0){
      closesuggest();
   }else{
      searchSuggest(1,'hbselectbtn');
   }
   document.FM.WO.focus();
}

function setKeywords (){
   var result = "";
   nc("#detail-keywords .check:checked").each( function () {
      if (result!="") result = result + "+";
      result = result + nc(this).val();
   });
   nc('#sidebar-right-searchform [name=KEYWORDS]').val(result);
   change_send_button();
   //document.BOXFORM.submit();
}

function imageLoadError(theImage,url) {
   msg = '<br/><strong>Leider kann das ausgewählte Bild zur Zeit nicht angezeigt werden.</strong><br/>';
   msg+= '<a href="#" onclick="Open(re_url,\'missing_image\')>Hier finden Sie weitere Bilder und Informationen zu diesem Angebot.</a>';
   
   nc('#dhtmlWindow .drag-contentarea').height(55);
   nc('#PopupManagerImgContainer').html(msg);
}

function select_all_text(el){
   el.focus();
   el.select();
}
function set_color(id, color){
   nc(id).css("color",color);
}

var ImmobiloCompareExpose = {
		updateCheckboxes: function () {
			nc('.compare-expose-checkbox').removeAttr('checked');
			for (var i = 0; i < siteSettings.exposeCompare.length; i++) {
				nc('#compare-expose-' + siteSettings.exposeCompare[i]).attr('checked', 'checked');
			}
		},
		request: function (url) {
			nc('#expose-compare-popup').dialog('close').html('').addClass('loader').dialog('option', 'position', [(nc('#Main').offset().left + nc('#Main').width() - 240), 'center']).dialog('open');
			nc.get('/dynamic/vergleichen/' + url, {}, function(data, textStatus) {
				
				if (data.html !== 'undefined' && data.exposeCompare !== 'undefined') {
					siteSettings.exposeCompare = data.exposeCompare;
					ImmobiloCompareExpose.updateCheckboxes();
					nc('#expose-compare-popup').html(data.html);
				}
				
				nc('#expose-compare-popup').removeClass('loader').parents('.ui-dialog').
				css({'height': nc('#expose-compare-popup .expose-compare-listing').outerHeight() + 120 + 'px'});
			}, 'json');
		},
		add: function(id) {
			ImmobiloCompareExpose.request('add/' + id); 
	    },
	    remove: function(id) {
	    	ImmobiloCompareExpose.request('remove/' + id);
	    },
	    remove_all: function() {
	    	ImmobiloCompareExpose.request('remove_all');
	    },
	    popup: function(operation) {
	    	ImmobiloCompareExpose.request('popup');
	    },
	    toggle: function (checkbox) {
	    	___idattr = nc(checkbox).attr('id').match(/(K|M)\d+$/)[0];
	    	if (nc(checkbox).attr('checked')) {
	    		ImmobiloCompareExpose.add(___idattr);
	    	}
	    	else {
	    		ImmobiloCompareExpose.remove(___idattr);
	    	}
	    }
};

var ImmobiloMySearchNew = {
	request: function(form) {
		nc('#new-search-popup').dialog('close').html('').addClass('loader').dialog('open');
		// .dialog('option', 'position', ['120px', 'center'])
		nc.post('/wohnen/new_email_alert.php', jQuery(form).serialize(), function(data, txtStatus, XHRResp) {
			nc('#new-search-popup').html(data);
			nc('#new-search-popup').removeClass('loader').parents('.ui-dialog');
		}, 'html');
		return false;
	},
	reload: function() {
		ImmobiloMySearchNew.hide();
		document.location.reload();
	},
	hide: function() {
		nc('#new-search-popup').dialog('close').html('');
	}
};

function hb_select_region(el){
   var val = nc('#detail-ort select[name='+el.name+']').val();
   var txt = nc('#detail-ort select[name='+el.name+'] :selected').text();
   nc('#detail-ort input[name=IDL]').val(val);
   nc('#detail-ort input[name=WO]').val(txt);
   onch_hb(el);
}

