jQuery(window).load(function(){
});

jQuery(document).ready(function(){
  /* IE6 check */
  if (typeof(ie6) != "undefined" && $.cookie('ie6_check') == null) {
    document.location.href = shop.baseUrl + 'browserError';
    //document.location.href = 'http://www.schlafwelt.de/browserError';
  }

  // browser-update.org nicht im Checkout anzeigen
  if ($('#progressbar').size() == 0) {
    var $buoop = {};
    $buoop.ol = window.onload; 
    window.onload=function(){ 
    if ($buoop.ol) $buoop.ol(); 
    var e = document.createElement("script"); 
      e.setAttribute("type", "text/javascript"); 
      e.setAttribute("src", "//browser-update.org/update.js"); 
      document.body.appendChild(e); 
    };
  }
  /* IE6 check end */
  
  // nmAG - Einbinden der Suggestsuche
  if($('#searchSuggestInput').size()>0)
    $('#searchSuggestInput').suggest(shop.baseUrl+'search/suggest');
  
  // nmAG - Aufruf des ADS-Expanders muss vor der Overlay/Glossar-Logik passieren, da es sonst zu Problemen mit dem Layern kommt
  if ($('#article_description #article_details').size()>0) {
    $('#article_description #article_details').expander({
      slicePoint: 260,
      widow: 10,
      expandText: 'mehr erfahren',
      userCollapseText: 'Details ausblenden'
    });
    $('span.re-collapse').before($('#article_additional'));
  }

  // initial call and interval for the sunset function (updated every minute)
  global.sunset('#sunset p');
  window.setInterval( function() { global.sunset('#sunset p'); }, 60000 );

  // init homepage teaser
  if (typeof(ie7) != 'undefined' || typeof(ie8) != 'undefined') { $('#home_a').fader({ fadeSpeed_gui: 0 }); }
  else { $('#home_a').fader(); }
  
  // init content tabs
  jQuery('#brandshop div.box_information_content > ul').superSimpleTabs();
  jQuery('div.tabs_type1 > ul').superSimpleTabs();
  jQuery('.js_indextabs').indextabs({
    onBeforeShow: function(navi, tabs, current, next) {
      // get headline
      var headline = navi.closest('.border').prev('h4');
      
      // save headline current
      headline.data('text_'+current, headline.html());

      // set saved headline current
      if (typeof(headline.data('text_'+next)) !== 'undefined') {
        headline.html(headline.data('text_'+next));
      } else {
        headline.find('.pagesCurrent').text('1');
      }
      
      var tabcontent = $(tabs).children('div:eq('+next+')');
      
      // there are differences between the sliders
      var carousel_class = tabcontent.children(":first").attr('class');
      var visible        = null;

      switch(carousel_class) {
        case 'carousel2':
          visible = 3; break;
        case 'carousel_pageable_4':
          visible = 4; break;
        case 'carousel_pageable_3':
          visible = 3; break;
        default:
          visible = 4; break;
      }
      
      headline.find('.pagesTotal').text(Math.ceil(tabcontent.find('li').size() / visible));
    }
  });  

  // init article comparison
  global.initArticleComparison('#article_comparison');

  // init carousel
  global.initCarousel('div.carousel div.js, div.carousel2 div.js, div.carousel_pageable_3 div.js, div.carousel_pageable_4 div.js, div.carousel_service div.js');

  // init navigation
  global.initNavigation();

  // turn select boxes into slider
  global.initSlider('div.slider');

  // handle ext. filter boxes
  global.initFilter();

  // handle overlay boxes
  global.initOverlay();

  // handle tooltips
  global.initTooltip();

  // handle tinytips
  global.initTinytip();

  // handle modals
  global.initModal('div.overlay_items div.modalOverlay'); //nmAG - Selector changed

  // star rater
  global.initStarRater('#article_detail_third_row div.star_rater');

  // checkout settings overlay
  global.checkoutSettings();

  // social bookmark icons
  global.initSocial();

  global.initRadioSlider();
  global.initCheckboxSlider();

  // autosized selector box
  global.initSelectorSize();

  //callback
  global.initCallback();

  // link areas from inner link
  global.initLinkArea('#customer ul.service_items a.hidden', 'li');

  // hardness calc
  global.initHardnessCalc();

  //24 hours service modal dialog
//  global.init24Hours('form.delivery_options');

  // form handling
    // masked input handling
    $('input.js_masked_date').mask("99.99.9999", { placeholder:'_' });

    // keyfilter handling
    $('input.js_filter_numeric').keyfilter(/[\d]/);
    $('input.js_filter_alpha').keyup(function(c) {
      this.value = this.value.replace(/\[|\]|\{|\}|\~/g, '');
    });
    
    $('input.js_filter_alpha').keyfilter(/[^\u201e\u201c\u00a7$%&\/=,.;:_+*<>|#?\[\]{}()"!~0-9]/i);
    $('input.js_filter_alphanumeric').keyfilter(/[^\u201e\u201c\u00a7$%&\/=,.;:_+*<>|#?\[\]{}()"!~]/i);
    
    
    $('input.js_filter_email').keyfilter(/[a-z0-9.!#$%&'*+-\/=?^_`{|}~@]/i);

    // configure validation plugin
    $.validator.addMethod('dateRegister', function (value, element) {
      var regex = /^\d\d\.\d\d\.\d\d\d\d$/;
      if (!regex.test(value)) return false;

      var parts = value.split('.');
      //console.log(parts);
      var day = parseInt(parts[0], 10);
      var month = parseInt(parts[1], 10)-1;
      var year = parseInt(parts[2], 10);

      var date = new Date(year, month, day);
      if (date.getTime() > new Date().getTime()) return false;

      var result = ((day==date.getDate()) && (month==date.getMonth()) && (year==date.getFullYear()));
      return result;
    });

    $.validator.setDefaults ({
      errorElement: "div",
      errorClass: "error",
      errorPlacement: function(error, element) {
        error.appendTo( element.closest('div.formRow'));
      },
      highlight: function(element, errorClass, validClass) {
        $(element).closest('div.formRow').addClass('error');
        $(element).addClass(errorClass).removeClass(validClass);
      },
      unhighlight: function(element, errorClass, validClass) {
        $(element).closest('div.formRow').removeClass('error');
        $(element).removeClass(errorClass).addClass(validClass);
        // count visible errors
        if ($(element).closest('div.simpleform div.formRow').find(':input.error').length > 0) {
          $(element).closest('div.simpleform div.formRow').addClass('error');
        }
      }
    });

    // "mark row" handling
    global.initFormRow('div.simpleform', 'div.formRow');

    // product customisation
    global.initProductCustomisation();
    
    // Einige seiteninterne Links dürfen keine Hash-änderung in der URL erzeugen 
    global.initHashReplacement('h4 a, #article_aside .toc a');
    
});

var global = {

    // nnAG: no price calculation in here, restrictions expanded, new function allFieldsEntered
    initProductCustomisation : function () {

  var disabledButton  = jQuery('#article_info div.button_arrow_l_disabled, .basket_handle_customisation div.button_arrow_l_disabled');
  var cartButton    = jQuery('#article_info a.button_arrow_l, .basket_handle_customisation a.button_arrow_l');
  var errorClass    = 'error';
  
  // first: ads page
  jQuery('#article_customisation input.validateCustomProduct').each(function (e) {

    $this = jQuery(this);

    $this.unbind();
    
    var restrictions  = getRestrictionsFromRel($this.attr('rel'));
    var errorDisplay  = $this.parent().find('.errorDisplay');

    $this.keyup(function(e) {
      var current = jQuery(this);
      
      if (!validateRestrictions(current.val(), restrictions)) {
        $('#measurementPriceDiv').hide();
        current.addClass(errorClass);
        errorDisplay.show();
      } else {
        current.removeClass(errorClass);
        errorDisplay.hide();
        $('#form_'+current.attr('name')).val(current.val());
      }

      // trigger global check
      handleCheckout('.article_customisation', errorClass);
    });


  });


  function handleCheckout(wrapper, errorClass) {
    if ((jQuery(wrapper + ' .' + errorClass).length > 0) || (!allFieldsEntered())) {
      // buttons
      cartButton.fadeOut('fast');
      disabledButton.fadeIn('fast');
    } else {
      disabledButton.fadeOut('fast');
      cartButton.fadeIn('fast');
      calculatePrice();
    }
  }



  // second: basket-handle-customisation
  var combinedErrorDisplay  = jQuery('#combinedErrorDisplay');
  var lastError       = null;
  jQuery('#basketHandleCustomisation input.validateCustomProduct').each(function (e) {

    var $this = jQuery(this);
    
    $this.unbind();
    
    var restrictions  = getRestrictionsFromRel($this.attr('rel'));
    var errorDisplay  = $this.parent().find('.errorDisplay');

    $this.bind('keyup focus', function (e) {
      var current = jQuery(this);
      
      //if (current.val().length > 0) {
        if (!validateRestrictions(current.val(), restrictions)) {
          $('#measurementPriceDiv').hide();
          current.addClass(errorClass);
          lastError = errorDisplay.html();
        } else {
          current.removeClass(errorClass);
          combinedErrorDisplay.html('');
          lastError = '';
        }
      //}

      // trigger global check
      handleCheckoutLayer('#basketHandleCustomisation', errorClass);
    });

  });


  function handleCheckoutLayer(wrapper, errorClass) {

    if ((jQuery(wrapper + ' .' + errorClass).length > 0) || (!allFieldsEntered())) {

      // buttons
      cartButton.fadeOut('fast');
      disabledButton.fadeIn('fast');

      // display last error
      combinedErrorDisplay.html(lastError);
      combinedErrorDisplay.show();
    } else {
      
      disabledButton.fadeOut('fast');
      cartButton.fadeIn('fast');
      combinedErrorDisplay.hide();
      calculateLayerPrice();
      combinedErrorDisplay.html('');
      lastError = '';
    }
  }



  function getRestrictionsFromRel(str) {

    if (str.length < 1)
      return;
    if (str == 'true' || str == true || str == 'false' || str == false)
      return str;
    var restrictions = str.split(',');
    if (restrictions.length != 3)
      return;
    
    for (i = 0; i < restrictions.length; i ++)
      restrictions[i] = parseInt(restrictions[i], 10);

    return restrictions;
  }

  function validateRestrictions(val, restrictions) {
    if (restrictions == 'false' || restrictions == false)
      return true;
    if (restrictions == 'true' || restrictions == true)
      return val != '';
    return ((val < restrictions[0]) || (val > restrictions[1]) || (val % restrictions[2] !== 0) || val == 'NaN') ? false : true;
  }
  
  function allFieldsEntered() {
    return !((($('#field1').attr('rel') != 'false' && $('#field1').attr('rel') != false) && $('#field1').val() == '') || (($('#field2').attr('rel') != 'false' && $('#field2').attr('rel') != false) && $('#field2').val() == '') || (($('#field3').attr('rel') != 'false' && $('#field3').attr('rel') != false) && $('#field3').val() == ''));
  }
  
  function calculatePrice() {
    if ($('#measurementPriceDiv').size() > 0) {
      var price = parseFloat($('#itemPrice').text().substring(0,$('#itemPrice').text().indexOf(' ')).replace(',','.'));
      if ($('#field1').val() != '')
        price = price * (parseInt($('#field1').val()) / 100);
      if ($('#field2').val() != '')
        price = price * (parseInt($('#field2').val()) / 100);
      $('#measurementPrice').text(price.toFixed(2).replace(".", ","));
      $('#measurementPriceDiv').show();
    }
  }
  
  function calculateLayerPrice() {
    if ($('#measurementPriceDiv').size() > 0) {
      var price = parseFloat($('#price').text().substring(0,$('#price').text().indexOf(' ')).replace(',','.'));
      if ($('#field1').val() != '')
        price = price * (parseInt($('#field1').val()) / 100);
      if ($('#field2').val() != '')
        price = price * (parseInt($('#field2').val()) / 100);
      $('#measurementPrice').text(price.toFixed(2).replace(".", ","));
      $('#measurementPriceDiv').show();
    }
  }

},

    

  initFormRow : function(parent_selector, row_selector) {
    $parent = $(parent_selector);

    // fixing z-index ie7 bug
    // http://brenelz.com/blog/squish-the-internet-explorer-z-index-bug/
    $parent.find('div.tooltipform').wrap('<div class="tooltipform_ie7fix"></div>');

    $parent.find(':input').bind('focus blur', function(e){
      $row = $(this).closest(row_selector);

      // toggle highglighting of row
      $row.toggleClass('highlight');

      // position formtooltip
      $row.find('div.tooltipform').toggle();

      // fixing z-index ie7 bug
      // http://brenelz.com/blog/squish-the-internet-explorer-z-index-bug/
      $row.find('div.tooltipform_ie7fix').toggleClass('zhigher');
    } );
  },
/*
  init24Hours : function(selector) {
    $form = jQuery(selector);
    if ($form.length === 0) return;
    $form.find('input[type=checkbox]').click(function(){
      // toggle sum and 0
      $(this).prev().find('span').toggleClass('hidden');

      // calculate total sum
      var total = 0;
      $form.find('div.summary strong span:visible').each(function(){
        var sum = $(this).text();
        total += parseFloat( sum.replace(/,/g, '.') );
      });
      total = String(total).replace(/\./g, ',');
      $form.find('p.totalsum span').text(total);
    });
  },
*/
  finishDesigner : function() {
    alert("Finish Designer");
  },

  sunset : function(selector) {
    var now = new Date;

    astronomy.init(53.5, 10, now);
    var sunset = astronomy.sunset();

    // get time difference in minutes
    var difference = sunset.getTime() - now.getTime();
    var difference = difference/1000/60;

    // get time diff
    var hours = Math.floor(difference/60);
    var minutes = Math.round(difference % 60);

    if (typeof jQuery(selector).data('sunset_string') == 'undefined') {
      jQuery(selector).data('sunset_string', jQuery(selector).html());
    }
    var html = jQuery(selector).data('sunset_string');
    if (html) {
      html = html.replace(/\[hours\]/, hours);
      html = html.replace(/\[minutes\]/, minutes);

      if (difference > 0) jQuery(selector).html(html).show();
    }
  },

  initArticleComparison : function(el_root) {
    var el_root   = jQuery(el_root);

    if (el_root.length == 0) return;

    var el_fields = jQuery('div.fields', el_root);
    var el_target = jQuery('ul.js_target', el_root);

    // get count for attributes
    var fields_count = jQuery('li', el_fields).length;

    // adjust heights of all li's
    // line for line
    for (var i=1; i<=fields_count; i++) {
      var max_height = 0;
      var hits = jQuery('> li:nth-child('+i+')', el_target).each(function() {
        var height = jQuery(this).innerHeight()-10; // 10px because of the padding of 5px at the top and bottom
        max_height = Math.max( height, max_height);
      });
      jQuery('ul.js_target:gt(0) > li:nth-child('+i+')', el_root).height(max_height);
      jQuery('ul.js_target:eq(0) > li:nth-child('+i+') div', el_root).height(max_height);
    }

    // add "show all attributes"
    el_fields.children('a').each(function() {
      jQuery(this).click(function(e) {
        e.preventDefault();
        jQuery('> li', el_target).show();

        // IE 7 Bug
        // http://stackoverflow.com/questions/33837/ie-css-bug-how-do-i-maintain-a-positionabsolute-when-dynamic-javascript-conten
        $('#canvas_base3 div.content_footer').css('display', 'none');
        $('#canvas_base3 div.content_footer').css('display', 'block');
      });
    });

    // add "hide attribute" feature to links
    jQuery('li a', el_fields).each(function(index) {
      jQuery(this).click(function(e) {
        e.preventDefault();
        jQuery('> li:nth-child('+(index+1)+')', el_target).hide();

        // IE 7 Bug
        // http://stackoverflow.com/questions/33837/ie-css-bug-how-do-i-maintain-a-positionabsolute-when-dynamic-javascript-conten
        $('#canvas_base3 div.content_footer').css('display', 'none');
        $('#canvas_base3 div.content_footer').css('display', 'block');
      });
    });
  },

  initSlider : function(selector) {
    $(selector).each(function() {
      var el = $(this);
      var js = el.find('div.js');
      var display = el.find('div.display');
      var el_handle = display.find('input[name="handle"]');
      var el_handle2 = display.find('input[name="handle2"]');

      var min = js.find('.min').remove();
      var max = js.find('.max').remove();
      var min = parseInt(min.text());
      var max = parseInt(max.text());
      var max_offset = Math.floor(((max-min)*.135)/2);
      max = max + max_offset;

      var initial_min = parseInt(el_handle.val());
      var initial_max = parseInt(el_handle2.val());

      var range = Math.floor(max-min);
      var closest_distance = 0;//Math.floor(((max-min)*.135));
      /*var step = Math.floor(range/30); nmAG - fÃ¼hrt bei zu kleiner Preisdifferenz zu 0 und macht den Preisslider funktionsuntÃ¼chtig */
      var step = 1;
      //adjust difference
      initial_min = initial_min - closest_distance;
      initial_max = initial_max + closest_distance;

      // allow only specific content
      display.find('input').keyfilter(/[\d,]/);

      // default options
      var slider_options = {
        step: step,
        min: min,
        max: max
      };

      // set options
      // multirange slider
      if (el_handle2.length > 0)  {
        slider_options.range = true;
        slider_options.values = [ initial_min, initial_max ];
        el_handle.change(function (e) {
          e.preventDefault();
          val = parseInt(el_handle.val());

          val_min_fallback = parseInt(el_handle2.val());
          if(val > val_min_fallback) val = val_min_fallback;
          if(val < min+closest_distance) val = min+closest_distance;

          el_slider.slider('values', 0,val);
          el_handle.val( val);
        });
        el_handle2.change(function (e) {
          e.preventDefault();
          val = parseInt(el_handle2.val());

          val_min_fallback = parseInt(el_handle.val());

          if(val < val_min_fallback) val = val_min_fallback;
          if(val > max-closest_distance) val = max-closest_distance;

          el_slider.slider('values', 1, val);
          el_handle2.val( val);
        });

        slider_options.slide = function(event, ui) {
          var val_min = ui.values[0];
          var val_max = ui.values[1];

          // handles should not overlap so we have to handle it
          // determine actual used handle
          var handle = 'first';
          if ($(ui.handle).hasClass('ui-slider-handle-last'))
            handle = 'last';

          // min handle is used
          val_min_fallback = val_max - closest_distance;
          if (handle == 'first' && val_min > val_min_fallback) {
            el_slider.slider('values', 0, val_min_fallback);
            el_handle.val( val_min_fallback );
            return false;
          }

          // max handle is used
          val_max_fallback = val_min + closest_distance;
          if (handle == 'last' && val_max < val_max_fallback) {
            el_slider.slider('values', 1, val_max_fallback);
            el_handle2.val( val_max_fallback );
            return false;
          }
          // max handle is used
          real_max = max - max_offset;
          if (handle == 'last' && val_max > real_max) {
            el_slider.slider('values', 1, real_max);
            el_handle2.val( real_max );
            return false;
          }


          el_handle.val( val_min + closest_distance );
          el_handle2.val( val_max - closest_distance );
        };
      }
      // simple slider
      else {
        slider_options.value = initial_min;
        slider_options.slide = function(event, ui) {
          el_handle.val( ui.value );
        };
      }





      // create slider
      var el_slider = $('<div></div>').slider( slider_options );

      // add classes to handles to style them differently
      el_slider.find('a.ui-slider-handle:first').addClass('ui-slider-handle-first');
      el_slider.find('a.ui-slider-handle:last').addClass('ui-slider-handle-last');

      // append slider
      el_slider.prependTo(js);

      // append go button
      var goButton = $('<a href="#" class="slider-submit">go</a>');
      goButton.bind('click', function printHandleValues() {
        var min = el_handle.val().split('\xa0')[0];
        var max = el_handle2.val().split('\xa0')[0];
        var cur = $('div.slider').find('div.currency').text();
        var gesamt = min + ' ' + cur + '-' + max + ' ' + cur;

        shopAction.changeFilter(gesamt);
      });
      goButton.appendTo( $(this) );

      // update display
      el_handle2.addClass('ui-slider-handle-last');
      el_handle.addClass('ui-slider-handle-first');
    });
  },


  initNavigation : function() {
    var el_navi = jQuery('#navi > ul > li');

    if (el_navi.length == 0) return;

    jQuery('> a', el_navi).click( function(e) {
      e.preventDefault();

      // do not trigger action at click on the theme element
      if (jQuery(this).hasClass('theme')) return;
      
      // do not trigger action at click on the active element
      if (jQuery(this).hasClass('active')) return;

      // hide all open lists
      jQuery('> ul', el_navi).slideUp().prev().removeClass('active');

      // open clicked list
      jQuery(this).addClass('active').next().slideDown();

      // close search
      jQuery('#search > form > a').removeClass('active').next().slideUp();
    });
    jQuery('> ul', el_navi).hide();
    jQuery('#navi a.active').next().show();
  },

  initCarousel : function(divs) {
    $(divs).each( function() {
      var el_carousel = $(this).parent();

      var el_info   = $('#'+el_carousel.attr('data-pager-info'));
      var el_pages_total   = el_info.find('span.pagesTotal');
      var el_pages_current = el_info.find('span.pagesCurrent');

      // there are differences between the sliders
      var carousel_class = el_carousel.attr('class');
      var visible        = null;
      var scroll         = null;

      switch(carousel_class) {
        case 'carousel2':
          visible = 3; scroll  = 1; break;
        case 'carousel_pageable_4':
          visible = 4; scroll  = 4; break;
        case 'carousel_pageable_3':
          visible = 3; scroll  = 3; break;
        case 'carousel_service':
          visible = 4; scroll  = 4; break;
        default:
          visible = 4; scroll  = 1; break;
      }
      
      // add empty items to get a total count that is a multiplier of visible (jCaousel Lite does not support remains)
      var el_lis      = $('> ul > li', this);
      var missing = el_lis.length % visible;
      if (missing != 0) {
        missing = visible - missing;
        for (var i=0; i < missing; i++) {
          el_lis.parent().append($('<li>&nbsp;</li>'));
        }
      }
            
      var el_prev     = el_carousel.find('a.prev');
      var el_next     = el_carousel.find('a.next');
      var el_first    = $('> ul > li:first-child', this).get(0);
      var el_last     = $('> ul > li:last-child', this).get(0);
      var el_lis      = $('> ul > li', this);
      
      // show "page current of total"
      if (el_carousel.is(':visible') && el_pages_total.length > 0) {
        var total = 1;
        
        if(el_lis.length > visible) {
          total = Math.ceil(el_lis.length / visible);
        }
        
        el_pages_total.text(total);
      }
      
      if(el_pages_current.length > 0) {
        el_pages_current.text(1);
      }
      
      // hide "previous" because we start with the first item
      el_prev.hide();

      // a special case if there are less elements as should be visible
      if (el_lis.length <= visible) {
        // should we hide "next"
        el_next.hide();
        el_prev.hide();
      }

      // actions on next/previous buttons
      el_prev.click(function(e) {e.preventDefault();});
      el_next.click(function(e) {e.preventDefault();});

      // load big images which are visible at startup
      visible_elements = el_lis.slice(0, visible);
      loadImages(visible_elements, visible);
      
      // load big images only when they get visible
      function loadImages(visible_elements, visible) {
        $('img[data-src]', visible_elements).each(function(){
          $(this).attr('src', $(this).attr('data-src')).removeAttr('data-src');
        });
      }
      
      // add carousel
      $(this).jCarouselLite({
        btnNext: el_next,
        btnPrev: el_prev,
        visible: visible,
        scroll:  scroll,
        afterEnd: function(visible_elements) {
          // callback to fade in/out prev/next buttons
          el_prev.fadeIn();
          if (el_first == visible_elements[0]) { el_prev.fadeOut(); }
          el_next.fadeIn();
          if (el_last == visible_elements[visible_elements.length-1]) { el_next.fadeOut(); }
          
          // load big images only when they get visible
          loadImages(visible_elements, visible);

          // show "page current of total"
          var el_pages_total   = el_info.find('span.pagesTotal');
          var el_pages_current = el_info.find('span.pagesCurrent');
          var current_index = el_lis.index(visible_elements.get(0));
          var current_page = Math.floor((current_index + 1) / visible) + 1;
          el_pages_current.text(current_page);
          if(el_lis.length > visible) {
            total = Math.ceil(el_lis.length / visible);
          }
          el_pages_total.text(total);
        },
        circular: false
      });
    });
  },

  initFilter : function () {
    jQuery("#filter").each( function() {
      var filterContainer = jQuery(this);
      var filterOpen    = jQuery(this).find('a.filter_open');
      var filterClose   = jQuery(this).find('a.filter_close');
      var filterReset   = jQuery(this).find('a.filter_reset');
      var selects     = jQuery(this).find('.filter.secondary');

      // clickevents
      filterClose.click(function (e) {e.preventDefault(); selects.addClass('hidden'); filterOpen.show(); filterClose.hide();});
      filterOpen.click(function (e) {e.preventDefault(); selects.removeClass('hidden'); filterOpen.hide(); filterClose.show();});
      filterReset.click(function (e) {
        e.preventDefault();

        jQuery("div.filter").each( function() {
          var clearForm = jQuery(this).find('form');
          global.clearForm(clearForm);
        });

      });

      // handle startup behaviour
      if (filterContainer.hasClass('contentOpen')) {
        selects.removeClass('hidden');
        filterOpen.hide();
      } else {
        selects.addClass('hidden');
        filterClose.hide();
      }


    });
  },

  /* a very usable overlay function
  initOverlay : function () {
    jQuery("div.articleMouseover").each( function() {
      var $this       = jQuery(this);
      var article       = $this.prev();
      var articleItem     = $this.closest('li');
      var canvas        = jQuery('#canvas');
      var offset        = 10;

      article.mouseenter(function(){
        $this.css('display', 'block');
      }).mousemove(function(e){
        var relative_offset   = jQuery('#content').offset(); // this is the first parent with a set position
        var window_dim      = { width: jQuery(window).width(), height: $(window).height() }; // browser viewport

        // set default position
        $this.css( { left: e.pageX - relative_offset.left + offset, top: e.pageY - relative_offset.top + offset } );

        // get mouseover dimensions
        dim = { width: $this.width(), height: $this.height() };

        // set position if there is no space on the right side
        if (e.pageX + dim.width + offset > window_dim.width) $this.css('left', e.pageX - relative_offset.left - offset - dim.width );

        // set position if there is no space on the bottom side
        if (e.pageY + dim.height + offset > window_dim.height) $this.css('top', e.pageY - relative_offset.top - offset - dim.height );
      }).mouseleave(function(){
        $this.css('display', 'none');
      });
    });
  },
  */

  initOverlay : function () {
    // cause of a bug in IE7 (see http://www.kontain.com/fi/entries/59209/browsers-gone-wild/)
    // we have to give the div.articleMouseover a background with a transparent pixel
    // to get the mouseleave event work correctly.
    jQuery("div.articleMouseover").each( function() {
      var $overlay      = jQuery(this);
      var article       = $overlay.prev();
      var $li         = $overlay.closest('li');
      var offset        = 0;

      $li.mouseenter(function(e){
        $overlay.css('display', 'block');
      }).mouseleave(function(e){
        $overlay.css('display', 'none');
      });

      article.mousemove(function(e){
        relative_offset   = jQuery('#content').offset(); // this is the first parent with a set position
        window_dim      = { width: jQuery(window).width(), height: $(window).height() }; // browser viewport
        dim = { width: $overlay.width(), height: $overlay.height() }; // get mouseover dimensions

        // set default position
        var css_rules = { left: e.pageX - relative_offset.left + offset, top: e.pageY - relative_offset.top + offset };

        // set position if there is no space on the right side
        if (e.pageX + dim.width + offset > window_dim.width) css_rules.left = e.pageX - relative_offset.left - offset - dim.width;

        // set position if there is no space on the bottom side
        if (e.pageY + dim.height + offset > window_dim.height) css_rules.top = e.pageY - relative_offset.top - offset - dim.height;

        $overlay.css(css_rules);
      });

      $overlay
        .css('cursor', 'pointer')
        .click(function(){
          document.location.href = jQuery(article).find('a').attr('href');
        });
    });
  },

  /*
  initTooltip : function(e) {
    $('body').append('<div id="tooltip"><div class="inner"><div class="headline">Info</div><div class="content">Test</div></div></div>');
    var el_tooltip = $('#tooltip');
    var el_tooltip_content = $('.content', el_tooltip);

    $('a.tooltip').each(function() {
      var el_trigger = $(this);

      // copy title content to data object
      el_trigger.data('title', el_trigger.attr('title')).removeAttr("title");

      // add events
      el_trigger
        .mouseover(function() {
          el_tooltip_content.text( el_trigger.data('title') );
          el_tooltip.show();
        })
        .mousemove(function(e) {
          var top = e.pageY - el_trigger.height() - el_tooltip.height() - 25; // 25 because of the sliding door padding
          var left = e.pageX - 125; // 125 because of the width of 250px
          el_tooltip.css( { left: left, top: top } );
        })
        .mouseout(function() {
          el_tooltip.hide();
        });
    });
  },
  */
  initTooltip : function(e) {
    jQuery('body').append('<div id="tooltip"><div class="inner"><div class="headline">Info</div><div class="content">Test</div></div></div>');
    var el_tooltip      = jQuery('#tooltip');
    var el_tooltip_content  = jQuery('.content', el_tooltip);
    var viewport      = getPageScroll();

    jQuery('a.tooltip').each(function() {
      var el_trigger = jQuery(this);

      // copy title content to data object
      el_trigger.data('title', el_trigger.attr('title')).removeAttr("title");

      // add events
      el_trigger
        .mouseover(function() {
          // update viewport scroll position
          viewport = getPageScroll();

          el_tooltip_content.html( el_trigger.data('title') );
          el_tooltip.show();

        })
        .mousemove(function(e) {
          var top;

          // determine distance to viewports top boundary
          var topEdge = e.pageY - el_tooltip.height() - el_trigger.height() - 25;

          if(topEdge - viewport[1] < 0) {
            top = e.pageY + el_trigger.height() + 15;
            jQuery(el_tooltip).addClass('below');
          } else {
            top = e.pageY - el_trigger.height() - el_tooltip.height() - 25; // 25 because of the sliding door padding
            jQuery(el_tooltip).removeClass('below');
          }

          var left = e.pageX - 125; // 125 because of the width of 250px
          el_tooltip.css( { left: left, top: top } );
        })
        .mouseout(function() {
          el_tooltip.hide();
        });
    });

    function getPageScroll() {
      var xScroll, yScroll;
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
      } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
      }

      return new Array(xScroll,yScroll);
    }

  },

  initTinytip : function(e) {
    jQuery('body').append('<div id="tinytip"><div class="inner"><div class="content"></div></div></div>');
    var el_tinytip      = jQuery('#tinytip');
    var el_tinytip_content  = jQuery('.content', el_tinytip);
    var viewport      = getPageScroll();


    jQuery('a.tinytip').each(function() {
      var el_trigger = jQuery(this);

      // copy title content to data object
      el_trigger.data('title', el_trigger.attr('title')).removeAttr("title");

      // add events
      el_trigger
        .mouseover(function() {
          // update viewport scroll position
          viewport = getPageScroll();

          el_tinytip_content.text( el_trigger.data('title') );
          el_tinytip.show();

        })
        .mousemove(function(e) {
          var top;

          // determine distance to viewports top boundary
          var topEdge = e.pageY - el_tinytip.height() - el_trigger.height() - 25;

          if(topEdge - viewport[1] < 0) {
            top = e.pageY + el_trigger.height() + 15;
            jQuery(el_tinytip).addClass('below');
          } else {
            top = e.pageY - el_trigger.height() - el_tinytip.height() - 25; // 25 because of the sliding door padding
            jQuery(el_tinytip).removeClass('below');
          }

          var left = e.pageX - 75; // 75 because of the width of 150px
          el_tinytip.css( { left: left, top: top } );
        })
        .mouseout(function() {
          el_tinytip.hide();
        });
    });

    function getPageScroll() {
      var xScroll, yScroll;
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
      } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
      }

      return new Array(xScroll,yScroll);
    }

  },


  initModal : function(selector) {
    var overlay = jQuery(selector);

    if (overlay.length == 0) return;

    overlay
      .appendTo('body')
      .css({ display: 'none', visibility: 'visible' })
      .find('a.jsclose').click(function(e) { e.preventDefault(); });

    jQuery(".modalSwitch a[rel], .modalSwitch div[rel]").each(function() {
      api = $(this).overlay({
        absolute: false,
        top: 'center',
        zIndex: 10002,
        close: 'a.jsclose',
        api: true,
        expose: {
          color: '#000',
          loadSpeed: 'normal',
          opacity: 0.1,
          zIndex: 10001
        }
      });

      if (api.getOverlay().hasClass('open')) api.load();
    });
    
    // nmAG - mantis Ticket #56660 - nicht zu entfernender Overlay
    jQuery(".modalSwitch_noClose a[rel], .modalSwitch_noClose div[rel]").each(function() {
      api = $(this).overlay({
        absolute: false,
        top: 'center',
        zIndex: 10002,
        close: 'a.jsclose',
        closeOnClick: false,
        closeOnEsc: false,
        api: true,
        expose: {
          color: '#000',
          loadSpeed: 'normal',
          opacity: 0.1,
          zIndex: 10001
        }
      });

      if (api.getOverlay().hasClass('open')) api.load();
    });
    
    
  },

  clearForm : function(form) {
    jQuery(':input', form).each(function() {
      var type  = this.type;
      var tag   = this.tagName.toLowerCase();

      if (type == 'text' || type == 'password' || tag == 'textarea') {
        this.value = "";
      } else if (type == 'checkbox' || type == 'radio') {
        this.checked = false;
      }

    });

    jQuery(':select', form).each(function() {
      var tag   = this.tagName.toLowerCase();
      if(tag=='select'){
        // reset form elements
        this.selectedIndex = 0;

        // update stylish select box as well
        var resetValue = this.options[this.selectedIndex].text;
        jQuery('select.improved').getSetSSValue(resetValue);
      }
    });

  },

  initStarRater : function(selector) {

    var value = -1;
    var el_root   = $(selector);

    if (el_root.length == 0) return;

    var el_select = $('select', el_root);
    var el_list   = $('<ul></ul>');
    var el_value  = $('<div></div>');

    // create html construct
    el_root.append( el_list ).append(el_value);

    // hide old select
    el_select.addClass('hidden');

    // create list elements from options
    var values = new Array();
    $('option:gt(0)', el_select).each(function() {
      el_list.append(
        $('<li />').text($(this).text())
      );
    });
    var els_li = $($('li', el_list));

    // global function to update star visualization
    var update = function(index) {
      els_li.removeClass('active');
      els_li.filter(':lt('+(index+1)+')').addClass('active');
      el_value.text( els_li.eq(index).text() );
    };

    // add mousemove control
    els_li
      .mousemove(function(e) { update( els_li.index(e.target) ); })
      .click(function(e) {
        value = els_li.index(e.target);
        el_select.children().removeAttr('selected');
        el_select.children(':eq('+(value+1)+')').attr('selected', 'selected');
      });

    // set to actual value
    el_list.mouseleave(function() { update( value ); });

  },


        initSocial : function() {

            var output      = '';
            var pageUrl     = encodeURIComponent(location.href);
            var pageTitle   = encodeURIComponent(document.title);
            var imagePath               = 'images/icons/';
            var shareObjects  =
                {"google": {
                    "url":"http://www.google.com/bookmarks/mark?op=add&hl=de&bkmk=" + pageUrl + "&annotation=&labels=&title=" + pageTitle,
                    "options":""
                    },
                "delicious": {
                    "url":"http://delicious.com/save?v=5&noui&jump=close&url=" + pageUrl + "&title=" + pageTitle,
                    "options":"toolbar=no,width=550,height=550"
                },
                "twitter": {
                    "url":"http://www.twitter.com/schlafwelt",
                    "options":""
                },
                "mrwong": {
                    "url":"http://www.mister-wong.de/index.php?action=addurl&bm_url=" + pageUrl + "&bm_description=" + pageTitle,
                    "options":""
                },
                "facebook": {
                    "url":"http://www.facebook.com/sharer.php?u=" + pageUrl + "&t=" + pageTitle,
                    "options":"toolbar=0,status=0,width=626,height=436,resizable=yes,scrollbars=yes"
                }

            };

            for (var key in shareObjects) {
                output = output + '<a rel="nofollow" class="' + key + '" href="#" onclick="javascript:window.open(\'' + shareObjects[key]['url'] + '\', \'' + key + '\', \'' + shareObjects[key]['options'] + '\');return false;">' + key + '</a>';
            }

            jQuery('#social_icons').html(output);

        },

        checkoutSettings : function () {
            if (jQuery("#overlayDeliveryOptions").length == 0) return;

            // Usage:
            // input radio name=delivery_address with value=delivery_address_shop disables:
            // radio=payment_method with value=payment_method_cash[, "or_any_other_additional_value"]
            var radioDisable = {};
            radioDisable.delivery_address = {'delivery_address_shop': {'payment_method': ['payment_method_cash']}};

            jQuery('fieldset.sourceSelector input:radio').each(function() {
               jQuery(this).click(function (e) {
                   handleState(this);
               });
            });

            function handleState(sourceElement) {
                // enable all
                jQuery('fieldset.targetSelector input:radio').removeAttr('disabled');

                for (var sourceValue in radioDisable[sourceElement.name]) {
                    if (sourceElement.value == sourceValue) {
                        // the element clicked is in definition and should disable something
                        for (var targetElement in radioDisable[sourceElement.name][sourceValue]) {
                            for (var targetValue in radioDisable[sourceElement.name][sourceValue][targetElement]) {
                                // finally
                                var v = radioDisable[sourceElement.name][sourceValue][targetElement][targetValue];
                                var jTargetElement = jQuery('fieldset.targetSelector input[name=' + targetElement + ']');

                                jTargetElement.each(function() {
                                    if (this.value == v) {
                                        jQuery(this).attr('disabled', true);
                                        this.checked = false;
                                    }
                                });
                            }
                        }
                    }
                }
            }




        },

        initRadioSlider : function () {

            jQuery('div.radioSlider').each(function() {

                $el = jQuery(this);
                var radio       = jQuery('input:radio', $el);
                var sliderDiv   = jQuery('div.slideable', $el);

                // initially hide every slider that has no open class
                // and check the radio box of opened boxes
                if (sliderDiv.hasClass('open')) {
                    radio.attr('checked', true);
                } else {
                    sliderDiv.hide();
                }

                radio.click(function() {
                   // in case this div is already open (has class "open") do nothing
                   if (!sliderDiv.hasClass('open')) {
                       // close all
                       jQuery('input:radio[name=' + this.name + ']').closest('div.radioSlider').find('div.slideable').each(function() {
                           jQuery(this).slideUp();
                           jQuery(this).removeClass('open');
                       });

                       sliderDiv.slideDown();
                       sliderDiv.addClass('open');
                   }
                });
            });

        },

        initCheckboxSlider : function () {

          jQuery('div.checkboxSlider').each(function() {

              $el = jQuery(this);
              var checkbox       = jQuery('input:checkbox', $el);
              var sliderDiv   = jQuery('div.slideable', $el);

              // initially hide every slider that has no open class
              // and check the checkbox box of opened boxes
              if (sliderDiv.hasClass('open')) {
                  checkbox.attr('checked', true);
              } else {
                  sliderDiv.hide();
              }

              checkbox.click(function() {
                 // in case this div is already open (has class "open") do nothing
                 if (!sliderDiv.hasClass('open')) {
                     sliderDiv.slideDown();
                     sliderDiv.addClass('open');
                 } else {
                     sliderDiv.slideUp();
                     sliderDiv.removeClass('open');
                 }
                });
            });

        },

        initSelectorSize : function () {
          // All browsers are capable of handling the size of dropdowns well
          // exept ie. Workaround makes dropdowns look ugly (arrow invisible),
          // so use this function only in ms browsers
          var userAgent = navigator.userAgent.toLowerCase();

          if (/msie/.test( userAgent ) && !/opera/.test( userAgent )) {

            // save size for reset
            var initSize = jQuery('select.autoSize:eq(0)').closest('div.filter').width();

            jQuery('select.autoSize').each(function () {
              $this = jQuery(this);

              // bind events
              $this.bind('focus mousedown', function(){ jQuery(this).width('auto'); });
              $this.bind('blur change', function(e){ jQuery(this).width(initSize); });
            });
          }
        },

        initLinkArea : function(link, area) {
          jQuery(link).each(function(){
            var link = $(this);

            link.closest('li')
              .css('cursor', 'pointer')
              .click(function(){
                if (link.attr('target') == null || link.attr('target') == '') //nmAG -Ãœbertrag der Verlinkung in ein neues Fenster
                  document.location.href = link.attr('href');
                else
                  window.open(link.attr('href'),link.attr('target'));
              });
          });
        },

        initCallback : function() {
          var currentDate   = new Date();
          currentDate.setHours(0);
          currentDate.setMinutes(0);
          currentDate.setSeconds(0);
          currentDate.setMilliseconds(0);

          var now     = new Date();
          // now     = parseInt((now.getHours().toString() + now.getMinutes().toString()),10);
          var buffer    = 15;
          var endDate     = new Date().setDate(currentDate.getDate() + 30);
          var endDate     = new Date(endDate);
          var holidays    = new Array();
          var years       = new Array();
          years.push(currentDate.getFullYear());


          for (var i = 0; i < years.length; i ++) {
            var sub   = [[1,1,years[i]],[1,5,years[i]],[3,10,years[i]],[24,12,years[i]],[25,12,years[i]],[26,12,years[i]],[31,12,years[i]], easterDate(years[i]), easterDate(years[i], -2), easterDate(years[i], 1), easterDate(years[i], 39), easterDate(years[i], 49), easterDate(years[i], 50)];
            holidays  = holidays.concat(sub);
          }

          // Datepicker setup
          jQuery("#callbackDate").datepicker({
            dateFormat :'d.m.yy',
            defaultDate : new Date(),
            dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
            dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
            monthNames: ['Januar', 'Februar', 'MÃ¤rz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
            nextText: 'nÃ¤chster Monat',
            prevText: 'vorheriger Monat',
            firstDay: 1,
            onSelect: date2input,
            beforeShowDay: validateCalDate,
            showOn: 'both',
            buttonImage: jQuery('#callbackDateTrigger').attr('src'),
            buttonImageOnly: true
          });

          // store data values for later usage
          jQuery('#callbackTime').data('options', jQuery('#callbackTime option'));

          // init layer -> set current date
          fillInput(currentDate.getDate() + '.' + (currentDate.getMonth() +1) + '.' + currentDate.getFullYear());

          jQuery('#callbackTime option:eq(0)').attr('selected', 'selected');

          //console.log(jQuery('#callbackTime option:eq(0)'));

          function date2input(dateText, inst) {
            fillInput(dateText);
            jQuery('#callbackDate').removeClass('error');

          }

          function fillInput(dateText) {
            handleTimeDropdown(dateText);
            jQuery('#callbackDate').val(dateText);
          }

          function handleTimeDropdown(dateObj) {

            var dateObj   = getDateObj(dateObj);
            var selector  = jQuery('#callbackTime');
            var today = ((currentDate.getDate() == dateObj.getDate()) && ((dateObj.getMonth() + 1) == currentDate.getMonth() +1) && (dateObj.getFullYear() == currentDate.getFullYear())) ? true : false;

            // first restore all values
            jQuery('option', selector).remove();
            selector.append(jQuery(selector).data('options'));

            // now remove, depending on saturdays && time
            // reassign "now" everytime!
            var now = new Date();
            now.setTime(now.getTime() + (1000 * 60 * buffer));

            jQuery('option', selector).each(function() {

              var optionTimestamp = jQuery(this).val().split('-')[0].split(':'); //nmAG .split('-')[0] hinzugefï¿½gt, da auch Endzeit mit angegeben ist

              if (today) {
                if  (parseInt(optionTimestamp[0], 10) < now.getHours() ||
                    (parseInt(optionTimestamp[0], 10) == now.getHours() && parseInt(optionTimestamp[1], 10) <= now.getMinutes())) {
                    jQuery(this).remove();
                  }
              }

              // remove time
              if (dateObj.getDay() == 6) {
                if (jQuery(this).attr('rel') == 'satEnd') {jQuery(this).remove();}
              }

            });

            if (jQuery('option', selector).length == 0) {
              jQuery(selector).hide();
              jQuery('#noCallbackPossible').show();
            } else {
              jQuery(selector).show();
              jQuery('#noCallbackPossible').hide();
            }


            return;
          }

          // validates textinput dates
          function validateInputDate(obj) {

            var dateRegEx   = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;

            if (!validateDate(jQuery(obj).val()) || !dateRegEx.test(jQuery(obj).val())) {
              jQuery(obj).addClass('error');
            } else {
              handleTimeDropdown(jQuery(obj).val());
              jQuery(obj).removeClass('error');
            }

            return;
          }

          // validation for cal display
          function validateCalDate(date) {
            return [validateDate(date), ''];
          }

          function validateDate(date) {

            var dateObj = getDateObj(date);

            // disable days further than 30 days and dates in the past
            if (dateObj.getTime() > endDate.getTime())
              return false;

            if ((dateObj.getTime()) < currentDate.getTime())
              return false;

            // disable sundays
            if (dateObj.getDay() == 0)
              return false;

            // disable holidays
            for (var i = 0; i < holidays.length; i ++) {
              if ((dateObj.getDate() == holidays[i][0]) && ((dateObj.getMonth() + 1) == holidays[i][1]) && (dateObj.getFullYear() == holidays[i][2]))
                return false;
            }

            return true;
          }


          function easterDate(year, offset) {

              if ((year == "") || (year == null))
                year = new Date().getFullYear();

              if ((offset == "") || (offset == null))
                offset = 0;

              var a = year % 19;
              var d = (19 * a + 24) % 30;
              var day = d + (2 * (year % 4) + 4 * (year % 7) + 6 * d + 5) % 7;
              if ((day == 35) || ((day == 34) && (d == 28) && (a > 10))) { day -= 7; }

              var easterDate = new Date(year, 2, 22);
              easterDate.setTime(easterDate.getTime() + 86400000 * offset + 86400000 * day);

              return new Array(easterDate.getDate(), easterDate.getMonth() + 1, easterDate.getFullYear());
          }

          function getDateObj(dateText) {
            if (typeof(dateText) != 'object') {
              var dateArray = dateText.split('.');
              return new Date(parseInt(dateArray[2], 10), parseInt(dateArray[1]) -1, parseInt(dateArray[0]));
            } else {
              return dateText;
            }
          }


          jQuery('#callbackDate').blur(function() {validateInputDate(this);});

          // nmAG - Wenn der aktuelle Tag ein Sonntag ist, muss die Fehlerbox sofort angezeigt werden
          if ($('#callbackDate').size() > 0)
            validateInputDate($('#callbackDate'));
        },

        initHardnessCalc : function () {
          var weight = 50;
          var height = 150;
          var hardness = 0;
          var fieldSuggest = jQuery('#hardness_calc_adjust');

          var fieldWeight   = jQuery('#hardness_calc_weight');
          var fieldHeight   = jQuery('#hardness_calc_height');
          var buttonMinus   = jQuery('#button_adjust_minus');
          var buttonPlus    = jQuery('#button_adjust_plus');

          var fieldInput    =  jQuery('#mattress_hardness');

          var buttonCalc    = jQuery('#button_hardness_calc');
          var buttonAccept  = jQuery('#button_hardness_accept');

          //define events
          fieldWeight.change(function (e) {e.preventDefault(); weight=this.value; fieldSuggest.val('');});
          fieldHeight.change(function (e) {e.preventDefault(); height=this.value; fieldSuggest.val('');});
          buttonPlus.click(function (e) {e.preventDefault(); adjustHardness(1); });
          buttonMinus.click(function (e) {e.preventDefault(); adjustHardness(-1); });
          buttonCalc.click(function (e) {e.preventDefault(); calcHardness();});
          buttonAccept.click(function (e) {
             e.preventDefault();
             value = hardness;
             if(value>5) value=5;
             if (value>2)
               fieldInput.val("H\u00e4rtegrad 3|H\u00e4rtegrad 4|H\u00e4rtegrad 5");
             else
               fieldInput.val("H\u00e4rtegrad "+value);
             fieldInput.change();
          });

          function calcHardness(){
            var heightm = height/100;
            var bmi = Math.round(weight / (heightm*heightm));
            if(bmi <= 25) hardness = 1;
            else if (bmi >= 35) hardness = 3;
            else hardness = 2;
            fieldSuggest.val(hardness);
          }

          function adjustHardness(offset){
            var value = hardness + offset;
            if(value >= 1 && value <= 5){
                                      hardness = value;
              fieldSuggest.val(hardness);
            }
          }
        },
        
        // Einige seiteninterne Links dürfen keine Hash-Änderung in der URL erzeugen 
        initHashReplacement: function(selector) {
          $(selector).click(function(e){
            e.preventDefault();
            if (this.hash == '') return false;
            
            // get target element
            var hash = this.hash.slice(1);
            var target = $('a[name="'+hash+'"]');
            if (target.length == 0) target = $('#'+hash);
            
            // scroll to offset of target element
            var offset = target.offset();
            scrollTo(offset.left, offset.top);
          });
        }

};

// chainable for effects because jQuery
// for other functions use the callback
$.fn.delay = function(time, callback) {
    return this.animate({ opacity: '+=0' }, time, callback);
};

// listen
$.fn.listen = function(event, selector, callback) {
    return $(this).bind(event, function(e){
    el = $(e.target).closest(selector, this);
    if (el.length) callback.call(this, e, el);
  });
};

