jQuery(document).ready(function ($) {

  var _msie6 = $.browser.msie && $.browser.version < 7;
  var _msie7 = $.browser.msie && $.browser.version >= 7;
  var _msie = _msie6 || _msie7;

  //alert('document ready');
  Pathnavigation = function(){

    var active = -1;
    var activating = -1;
    var navigation = $('#path .navigation:not(.sub)');
    var elemSelector = '#path .navigation:not(.sub) > li';
    var elements = $(elemSelector);
    var subNavigation = $('#path .navigation.sub');
    var subElemSelector = '#path .navigation.sub > li';
    var subElements = null;
    var handles = elements.filter('.dropdown');

    init();

    function init() {
      widthControl();
      dropDownCheck();

      if (0 < subNavigation.length) {
        subElements = $(subElemSelector);
        subWidthControl();
        handles = $(elemSelector + ',' + subElemSelector).filter('.dropdown');
      }


     if (_msie6) {
        handles.each(function(index) {
          var handle = $(this);
          if (0 < $('li', handle).length) {
            handle.hover(function() {
              $(this).addClass('hover');
            }, function(ev) {
              $(this).removeClass('hover');
            });
          }
        });
      }


    }

    function dropDownCheck() {
      handles.each(function() {
        if (0 == $('li', this).length) {
          // dropdown list can be empty accordingly to visibility settings for the user
          $(this).removeClass('dropdown');
          $('span.arrow', this).remove();
        }
      });
      elements.filter(':last').addClass('current');
    }

    function widthControl() {
      var i = 0, w = 0, x = 0, el;
      var j = navigation.width();
      var k = elements;
      var arrow = $(elemSelector + ' > a span.arrow:first');
      var widths = new Array();
      k.each(function(index) {
        el = $(this);
        w = el.width();
        widths[index] = w;
        w += (parseInt(el.css('border-left-width')) + parseInt(el.css('border-right-width')));
        i += w;
      });
      for (x; x < elements.length; x++) {
        if (i < j) {
          break;
        } else {
          el = $(k).get(x + 1);
          $(el).children('a').html('...&nbsp;').append(arrow.clone());
          i += $(el).width();
          i -= widths[x];
        }
      }
    }

    function subWidthControl() {
      var w = 0, allWidth = 0, showWidth = 0, el;
      var c = $('<div class="con"><ul></ul></div>');
      var i = subNavigation.width();
      
      if (_msie6) {
        $('li:first', subNavigation).css({
          borderWidth : '0'
        });
      }

      subElements.each(function(index) {
        el = $(this);
        w = el.width();
        w += (parseInt(el.css('border-left-width')) + parseInt(el.css('border-right-width')));
        w += (parseInt(el.css('padding-left')) + parseInt(el.css('padding-right')));
        allWidth += w;
        if (allWidth > i) {
          $('ul', c).append(el);
          if (0 == showWidth) {
            showWidth = allWidth - w;
          }
        }
      });
      if (allWidth > i) {
        if (showWidth + 100 > i) {
          // we need a little space between last item and more button
          $('ul', c).prepend($(subElemSelector).filter(':last'));
        }
        subNavigation.append('<li class="dropdown"><a href="#">mehr...&nbsp;</a></li>');
        $('.dropdown a', subNavigation).append($(elemSelector + ' > a span.arrow:first').clone());
        $('.dropdown', subNavigation).append(c);
        $('.dropdown .con', subNavigation).prepend($('.shadow:first').clone());
      }
    }

  };





 /**
   * class Haendlerforum Sitemap
   */

  $('a[href="#hfoDiv"]').parent().addClass('hfoLIDiv');
  $('.hfoLIDiv').hover(
    function () {
      $(this).find('.con').show();
    },
  	function () {
      $(this).find('.con').hide();
  	}
  );



  /**
   * class Sitemap bind an click event on the sitemap icon, initialize the
   * sitemap and provide tabbing functionality
   */
  Sitemap = function(){
    var link = $('#sitemap, a[href*="sitemap"]');
    var con = '#sitemapContainer';
    var tab = '.tab';
    var list = '.con';
    // var closeBut = $('img.closeBut', con);
	var closeBut = '#sitemapContainer img.closeBut';

    if (0 < link.length) init();

    /**
     * initialize the sitemap object
     */
    function init(){
      initTabs();
      initHFOLayer();

      link.click(function(){
        if (!window.location.pathname.match(/^\/offen.+/i)) { // offener Bereich im HFO ohne Sitemap
          if (!link.hasClass('active')) {
            link.addClass('active');
            if (0 == $(con).length) {
              $(this).after('<div id="sitemapContainer"><div style="height:300px;" class="loading"></div></div>');
              loadSitemapJSON();
            }
            lightbox(true, $(con));
          } else {
            lightbox(false);
          }
        }
        return false;
      });

      initCloseBut();
    }
    
    function loadSitemapJSON() {
      url = HTTP_HOST + '/ajax/sitemap.php' + '?jsonp=?';
      $.getJSON(url, function(data) {
        
        $(con).fadeOut(function() {
        
          $(this).html('<div class="con active"><div class="layer">' + data.headline 
            + data.closebut + '</div></div>');
          
          $(this).prepend($('.shadow:first').clone());
          
          var groups = '<div class="group">', placement = 1, i, item;
          
          for (i = 0; i < data.groups.length; i++) {
            item = data.groups[i];
            if (Number(item.placement) != placement) {
              groups += '</div><div class="group">';
              placement = Number(item.placement);
            }
            groups += item.headline;
            if (item.items) {
              groups += '<ul><li>' + item.items.join('</li><li>') + '</li></ul>';
            }
          };
          groups += '</div>';
          
          if (data.shopGroup) {
            groups += '<div class="group shop-group">'
              + data.shopGroup.headline
              + '<ul><li>' + data.shopGroup.items.join('</li><li>') + '</li></ul>'
              + '</div>';
          }
          $('.layer', con).append(groups);

          $(this).fadeIn('fast');
          initCloseBut();
          initHFOLayer();
        });
    });
    }
    
    function initHFOLayer() {
      if ($('a[href=#hfo]')) {
        $('a[href="#hfo"]').parent().addClass('hfoH3Div');
        $('.hfoH3Div').hover(function() {
          $(this).find(".con").show();
        }, function() {
          $(this).find('.con').hide();
        });
      }
    }
    
    function initCloseBut() {
      if (0 < $(closeBut).length) {
        $(closeBut).click(function() {
          lightbox(false);
          return false;
        });
      }
    }

    /**
     * initialize a simple tabbing behavior
     */
    function initTabs(){
      var tabs = $(tab, con);
      var cons = $(list, con);

      tabs.each(function(i){
        $(this).click(function(){
          if ($(this).not('.active')) {
            $(tabs).removeClass('active');
            $(cons).removeClass('active');
            $(this).addClass('active');
            var el = $(cons).get(i);
            $(el).addClass('active');
          }
        });
      });
    }

    /**
     * show or hide the lightbox and fade the tabs and layers in and out
     *
     * @param {Boolean} show - show or hide the lightbox
     * @param {String} elem -css-selector of the dom-element which controls the sitemap
     */
    function lightbox(show, elem){
      if (show) {
        var el = $('<div id="lightbox"></div>');
        var cont = $('#content');
        var contLeft = parseInt(cont.css('padding-left'));
        var contTop = parseInt(cont.css('padding-top'));
        var bw = 2; // 2 * border-width of the container
        var h = (parseInt(cont.height()) + contTop + parseInt(cont.css('padding-bottom')) + bw) + 'px';
        var w = (parseInt(cont.width()) + 2 * contLeft + bw) + 'px';
        el.css({
          height: h,
          width: w,
          left: '-' + (contLeft + bw /2) + 'px',
          top: '-' + (contTop + bw / 2) + 'px'
        }).click(function(){
          lightbox(false);
        });
        var lPath = parseInt($('#path').css('margin-left'));
        if (0 > lPath) {
          var tmp = parseInt(cont.css('padding-left'));
          tmp += lPath;
          tmp += bw / 2;
          lPath = -tmp;
          el.css({
            left: lPath + 'px'
          });
        }
        if (_msie6) {
          $('#content select, #path div.search').css({
            visibility: 'hidden'
          });
        }
        $('body').append(el);
        if (elem) {
          $(elem).before(el);
        }
        $(elem).fadeIn('fast');
      } else {
        $(con).fadeOut('fast', function(){
		  link.removeClass('active');
          $('#lightbox').remove();
          if (_msie6) {
            $('#content select, #path div.search').css({
              visibility: 'visible'
            });
          }
        });
      }
    }

  }

  /**
   * global object initializes and controls the stage
   */
  Stage = function () {
    var navigation = new Pathnavigation();
    var sitemap = new Sitemap();

    $('#head input[type=text], #suche-search-complete-0 input[type=text], #path input[type=text]').defaultvalue();

     // pngfix images with class pngfix
     if ($().pngfix) {
       $('img').filter('.pngfix').pngfix();
  /*     $('.bigBonus > img, .mediumBonus > img, .smallBonus > img, div.rounded-corners span').pngfix(); */
	   $('.bigBonus > img, .mediumBonus > img, .smallBonus > img, .abstracts .medium img').pngfix();
       }
  }

  /* preallocate textfields and textarea */
  $.fn.extend ({
    defaultvalue: function(){
      var element = $(this);
      element.each(function(){
        var el = $(this);
        var def = el.attr('title');
        var defcheck = new RegExp('^\\s*'+def+'\\s*$');
        el.focus(function(){
          if (el.val().match(defcheck)) {
            el.val("");
          }
          el.blur(function(){
            if ("" == el.val() || el.val().match(defcheck)) {
              el.val(def);
            }
          });
        });
      })
    }
  });

  /**
   * init stage
   */
  stage = new Stage();

  /**
   * quickaccess im page-header
   */
  initQuickAccessList('#head', false);
});

function initQuickAccessList(selector, modal) {
  if (modal) {
    jQuery('#TB_ajaxContent').addClass('showOverhead');
  }
  jQuery('.quickAccess > div', selector).hover(
    function() {
      jQuery('.container', this).stop(true, true).slideDown('fast');
    },
    function() {
      jQuery('.container', this).stop(true, true).slideUp('fast');
    }
  );
  jQuery('.quickAccess div p > a', selector).click(
    function(){ return false; }
  ).css({ cursor: 'text'});
  jQuery('.quickAccess div.infoEvents ul a', selector).click(
    function() {
      jQuery('.quickAccess div.infoEvents p', selector).removeClass('blink');
    }
  );
  if (0 < jQuery('div.subscriberSwitch', selector).length) {
    jQuery('.quickAccess div.subscriberSwitch p > a', selector).getsubscribers();
  }
}

