var className = 'js';
if (window.frameElement) {
    className += ' iframe';
}
document.documentElement.className = className;

/**
 * function for easy popup acces from a tag
 *
 * @param a
 *            tag
 * @param width
 *            the width of popup
 * @param height
 *            the height of popup
 * @param targetName -
 *            name of the popup
 */
(function ($) {
    $.openPopup = function (a, width, height, targetName) {
        width = width || 960;
        height = height || 680;
        targetName = targetName || 'buububub';
        a.target = targetName;
        var url = a.href || '';
        var options = 'width='+width+', height='+height+', location=0, resizable=0, menubar=0, status=0, toolbar=0, scrollbars=1';
        var popup = window.open(url, targetName, options);
        if (popup) {
            popup.focus();
        }
        return false;
    };
})(jQuery);


/**
 * jQuery.showDialog One argument, a hash of options: - title (optional, if
 * given, replaces
 * <h5> content) - text (optional, if given, empties all
 * <p>
 * and inserts text) - buttons (a hash of hashes like: button-text => onClick:
 * function, highlight: boolean) - content (optional, if given, points to the
 * dialog element to be shown; defaults to #feedbackContent) - height (optional,
 * default 200) - width (optional, default 400)
 */
(function ($) {
    $.showDialog = function (opt) {
        var href = opt.content || '#feedbackContent'; // href to inline
                                                        // anchor, not a
                                                        // selector!
        var content = $(href);
        if (!content.length) {
            content = $('<div>\
                    <div class="clearfix feedBack">\
                        <h5></h5>\
                        <p></p>\
                        <div class="clearfix send"></div>\
                    </div>\
                </div>\
            ');
        }
        content = content.find('.send').empty();
        arguments.callee.data = opt;
        $.each(opt.buttons, function (text) {
            var data = this;
            var button = $('<div class="buttonBg" title="' + text + '">\
                <a title="" href="#"><strong style="">' + text + '</strong></a>\
                </div>');
            if (!data.highlight) {
                button.addClass('buttonBgGrey');
            }
            button.attr('onclick', '\
                var oc = jQuery.showDialog.data.buttons["' + text + '"].onClick;\
                if (oc) {\
                    oc(function () {\
                        Shadowbox.close();\
                    });\
                } else {\
                    Shadowbox.close();\
                }\
                return false;\
            ');
            content.append(button);
        });
        var title = opt.title || '';
        if (title) {
            content.end().find('h5').html(title);
        }
        if (opt.text) {
            content.end().find('p').empty().eq(0).html(opt.text).end();
        }
        Shadowbox.open({
            content: content.end().html(),
            player: 'html',
            title: title,
            height: opt.height || 200,
            width: opt.width || 400,
            options: {
                skipSetup: true,
                modal: true,
                skinMode: 'noFooter'
            }
        });
    };
})(jQuery); // end $.showDialog



jQuery(document).ready(function(jQuery){
  
//ie < 9 -> expand select options to width needed (like all other browsers do)
// copy from http://stackoverflow.com/questions/73960/dropdownlist-width-in-ie
//  if ($.browser.msie && $.browser.version < 9) {
//    $('select.wide')
//    .bind('focus mouseover', function() { 
//      $(this).addClass('expand').removeClass('clicked'); 
//     })
//    .bind('click', function() { 
//      $(this).toggleClass('clicked'); 
//     })
//    .bind('mouseout', function() { 
//      if (!$(this).hasClass('clicked')) { 
//        $(this).removeClass('expand'); 
//      }
//     })
//    .bind('blur', function() { 
//      $(this).removeClass('expand clicked'); 
//     });
//  }

// ie < 7.0 kann kein li:hover
    if ($.browser.msie && $.browser.version < '7') {
        var ie6navigation = function (e) {
            if (this.hovering) {
                this.hovering = false;
            } else {
                this.hovering = true;
            }
            $(this).toggleClass('hover');
        };
        function buttonHover(e) {
            ie6navigation.call(this, e);
            $(this.parentNode).toggleClass(this.className);
        }
        function hideInputs(e) {
            ie6navigation.call(this, e);
            $(this).nextAll().find('input, select').toggle();
        }
        // $('ul.mainNavigation li').hover(ie6navigation, ie6navigation);
        $('.buttonBg').hover(ie6navigation, ie6navigation);
        $('.buttonBg input.button').hover(ie6navigation, ie6navigation);
        $('.buttonBg2').hover(ie6navigation, ie6navigation);
        $('.helpTab').hover(ie6navigation, ie6navigation);
        $('.showCase ul.pageList li').hover(ie6navigation, ie6navigation);

    }



    // Ausklappen des slidingContent
    $("div.slidingContent").hide();
    $("a.slideLink").click(function (){
        var link = $(this);
        link.blur().toggleClass("open").
                parent().next("div.slidingContent").slideToggle("fast");

        // text schublade
        var text = {
            open: 'Auswahl ändern',
            close: 'Schließen'
        };

        // text mehr im content
        if (link.hasClass('moreInfo')) {
            text = {
                open: '<span></span>Lesen Sie mehr',
                close: '<span></span>Beschreibung ausblenden'
            }
        }

        if (!link.hasClass('noToggleText')) {
            if (link.hasClass('open')) {
                link.html(text.close);
                link.attr('title', text.close)
            } else {
                link.html(text.open);
                link.attr('title', text.open)
            }
        }

        // fix for shopping cart
        link.closest('#header').toggleClass('shoppingCartOpen', link.hasClass('open'));

        return false;
    });


    // schublade onsubmit erst schließen; event-handler sendet sich selbst
    // event-daten um das finale senden zu erkennen
    $('div.personalization form').bind('submit', function (e, doSubmit) {
        if (doSubmit) {
            return true;
        }
        $(this).closest('div.slidingContent').slideUp('fast').queue(function () {
            $(this).find('form').trigger('submit', true).end().dequeue();
        });
        return false;
    });

    // tab-navigation: ENTWEDER per ajax oder mit vorproduzierten
    // div.contentArea
    $('div.contentNavigator ul.pageList a[href=#]').click(function (e) {
        var link = $(this);
        var matches = link.parent('li').attr('class').match(/tab_\w*/);
        if(matches.length > 0)	{
          $.cookie('showcase_selected', matches[0] );
        }
        var pageList = link.closest('ul.pageList');
        var include = link.parent().metadata().include;
        if (include) {
            pageList.next('div.contentArea').load(include);
        } else {
            var index = pageList.find('a').index(this);
            pageList.siblings('div.contentArea').addClass('hide').eq(index).removeClass('hide');
        }
        link.parent().addClass('selected').siblings().removeClass('selected');
        return false;
    });
    
    if($.cookie('showcase_selected') && $.cookie('showcase_selected').length)	{
      var selectClass = $.cookie('showcase_selected');
       $('div.contentNavigator ul.pageList li.'+ selectClass+' a').trigger('click');
    }
    
   

    // Content include in Guided Tour
    /*
     * $('a.includeLink').click(function (e) { var link = $(this); var
     * includeTarget = link.closest('.includeTarget');
     * includeTarget.load(link.attr('href')); e.preventDefault(); });
     */

    // top-nav langsam einfaden
    $('ul.mainNavigation > li').each(function (numLi) {
        var li = $(this);
        var layer = li.children('div.navLayer');
        var height = layer.outerHeight();
        var width = layer.outerWidth();
        layer.addClass('navLayerProcessed').css({
            width: width
        });
        li.hover(function (e) {
            layer.addClass('navLayerActive').stop().css({
                height: 0
            }).animate({
                height: height
            });
        }, function (e) {
            layer.removeClass('navLayerActive').stop().animate({
                height: 0
            });
        });
    });

    // toggle listenansicht suche
    $('a.sortView').click(function (e) {
        var link = $(this);
        if (link.hasClass('asGrid')) {
            link.closest('.listModul').addClass('grid');
        } else {
            link.closest('.listModul').removeClass('grid');
        }
        e.preventDefault();
    });

    // reiternav
    $('div.tabContainer').each(function (r) {
        var tabContainer = $(this);
        var alleReiter = tabContainer.find('li.tab');
        alleReiter.each(function (i) {
            var reiter = $(this);
            reiter.find('a').click(function (e) {
                tabContainer.find('div.tabContent').removeClass('tabBlock').filter(':eq(' + i + ')').addClass('tabBlock');
                alleReiter.removeClass('tabSelected');
                reiter.addClass('tabSelected');
                $.cookie('cvServiceBox_selected', reiter.attr('data-value'), {path: '/'});
                return false;
            });
        });
    });

    $('a.popupLink').click(function (e, data) {
        var params = '';
        switch (this.target) {
          case 'warenkorb':
            params = "width=800,height=750,toolbar=yes,location=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes";
            break;
            case 'servicebox':
                params = "width=800,height=750,toolbar=yes,location=yes,status=yes,menubar=yes,resizable=yes,scrollbars=yes";
                break;
            case 'download':
              params = "width=950,height=640,toolbar=0,location=0,status=0,menubar=yes,resizable=0,scrollbars=1";
            default:
        }
        fenster = window.open(this.href, this.target, params);
        if (fenster) {
            fenster.focus();
        }
        return false;
    });

    /**
     * enshure gridcontent heights are equal
     */
    $('#col3_subc_content .gridContent').each(function(index, gridContent)    {
        var first;
        var second;

        //textSections in grid
        $(gridContent).find('.textImage').each(function(index, textabschnitt)	{
            if(index % 2 == 1)	{
                second = $(textabschnitt);
                var targetHeight = Math.max(first.innerHeight(), second.innerHeight());
                first.height(targetHeight);
                second.height(targetHeight);
            }
            else	{
                first = $(textabschnitt);
            }
        });

    });




    /**
     * Initializes gallery modules with right-hand slider and shadowbox details.
     */
  $('div.galleryWithSlider').not('div.galleryWithSlider.media').each(function (numGallery) {

    // outer container of the gallery
        var slider = $(this);

    // updates preview image src and centers/resizes the image in the left hand container
    setPreviewImage = function (href, width, height) {
      var containerHeight = previewImage.parent().height();
      var containerWidth = previewImage.parent().width();
      var resultingHeight = height;
      var resultingWidth = width;
      if (height > width) {
        resultingHeight = Math.min(height, containerHeight);
        resultingWidth = resultingHeight / height * width;
      } else {
        resultingWidth = Math.min(width, containerWidth);
        resultingHeight = resultingWidth / width * height;
      }
      var top = Math.max(0, (containerHeight - resultingHeight) / 2);
      var left = Math.max(0, (containerWidth - resultingWidth) / 2);
      previewImage.css({
        top: top >>> 0,
        left: left >>> 0,
        height: resultingHeight >>> 0,
        width: resultingWidth >>> 0
      }).attr('src', href).fadeIn('fast');
    };

    // get shadowbox keys from freshly bound links and remove click handler
    var shadowboxKeys = slider.find('.detailLink').shadowbox({
      gallery: 'galleryWithSlider' + numGallery,
      skinMode: 'gallery'
    }).unbind('click').map(function () {
      return this.shadowboxCacheKey;
    });

    slider.rotate({
            api: false,
            isCircular: true,
            isGapless: false,
            itemsPerPage: 3,
            direction: 'vertical',
            selectBack: 'div.slideUp a',
            selectNext: 'div.slideDown a'
        });

    // bind click handler to preview image to the left, that opens shadowbox
    var previewImage = slider.find('.previewImage').bind('click', function (e) {
      Shadowbox.open(currentShadowbox);
    });

    // contains detail image to be shown on preview image click
    var currentShadowbox = null;

    // set preview image on click and select new detail shadowbox
    var detailLinks = slider.find('.detailLink').bind('click', function (e) {
      e.preventDefault();
      previewImage.fadeOut('fast');
        var item = $(this);
      var shadowboxKey = shadowboxKeys[detailLinks.index(item) % shadowboxKeys.length];
      currentShadowbox = Shadowbox.cache[shadowboxKey];
      var data = item.metadata();
      var img = new Image();
      img.onload = function () {
        setPreviewImage(data.previewImage, this.width, this.height);
      };
      img.src = data.previewImage;
        });

    // select first item on start
    detailLinks.eq(0).click();

  });




});
