/**
 **************************************************************************
 * Some global defined variables, which will be used in various templates
 **************************************************************************
 */
var barImage;
var barWidthTotal;
var barWidthSingle;
var barCounterValues;
var barBewertungenTotal;
var barCnt;
var hoverTimer;
var timer = null;
var buchhaendlerName = '';
var top100Counter = 1;
var topTitelCounter = 1;
var listenCounter = 1;
var galleryCounter = 0;
var slideShowTime = 3000;
var maxCharsForGrusskarte = 190;


/**
 **************************************************************************
 * This function hides content while fonts are loading
 * http://paulirish.com/2009/fighting-the-font-face-fout/
 **************************************************************************
 */
(function(){
  // if firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
  var d = document, e = d.documentElement, s = d.createElement('style');
  if (e.style.MozTransform === ''){ // gecko 1.9.1 inference
    s.textContent = 'body{visibility:hidden}';
    var r = document.getElementsByTagName('script')[0];
    r.parentNode.insertBefore(s, r);
    function f(){ s.parentNode && s.parentNode.removeChild(s); }
    addEventListener('load',f,false);
    setTimeout(f,3000);
  }
})();
// A nice improvement to this script is to only hide the elements using webfonts
// with visibility:hidden instead of the entire <body>
// that's up to you to select them in that textContent line, though


/**
 **************************************************************************
 * Function for Main Navigation
 **************************************************************************
 */
function initMainNav() {
    $('#contentNavigation #nav .liLevel1').mouseenter(function(){
        clearTimeout(this.hoverTimerOut);
        var elem = $(this);
        hoverTimer = setTimeout(function() {
            elem.addClass("navHover");
        }, 300);
    });
    $('#contentNavigation #nav .liLevel1').mouseleave(function(){
        clearTimeout(hoverTimer);
        var elem = $(this);
        if (elem.hasClass('navHover')){
        this.hoverTimerOut = setTimeout(function() {
            elem.removeClass("navHover");
        }, 300);
       }
    });
}


/**
 **************************************************************************
 * Function to create a XML request (used in the typhoon.js)
 **************************************************************************
 */
function BuchXmlHttp() {
    function createReq() {
        var request = null;
        if (window.ActiveXObject) {
            try {
                request = new ActiveXObject("Msxml2.XMLHTTP"); // MSIE 6.x
            } catch(e) {
                try {
                    request = new ActiveXObject("Microsoft.XMLHTTP"); // MSIE 5.x
                } catch(e) {
                    request = false;
                }
            }
        } else if (window.XMLHttpRequest) {
            try {
                request = new XMLHttpRequest();
            } catch(e) {
                request = false;
            }
        }
        return (request) ? request : null;
    }

    this.createReq = createReq;

    // Opens a request
    function openReq(request, url, callback) {
        request.open("GET", url);
        request.onreadystatechange = callback;
    }
    this.openReq = openReq;

    // Send a request
    function sendReq(request) {
        request.send(null);
    }
    this.sendReq = sendReq;
}


/**
 **************************************************************************
 * Function for hovering over the a slider element
 **************************************************************************
 */
function hoverCover() {
    var $covers = $('.productImgContainer');
    var $coverScreen = '<div class="productImgHoverCover"></div>';
    $covers.find('.productImgHover').append($coverScreen);
    $covers
    .hover(
        function(){
            var $self = $(this);
            clearTimeout(this.timer);
            $(this).find('.productImgHover').show('fast',function(){
                    $(this).find('.btShoppingCart').slideDown('fast');
            });
        },
        function(){
            var $self = $(this);
            this.timer = setTimeout(function(){
                $self.find('.btShoppingCart').slideUp('fast',function(){
                    $(this).parents('.productImgHover').fadeOut();
                });
            },500);
        })
    .bind('click', function(e){
        var eTarget = $(e.target).parent().attr('class');
        var linkHref = (eTarget == "btShoppingCart") ? $(this).parent().find('.btShoppingCart').attr('href') :  $(this).parent().find('.productImgLink').attr('href');
        window.location.href = linkHref;
        return false;
    });
}


/**
 **************************************************************************
 * Function for opening a popup
 **************************************************************************
 */
function  openFlexWindow (url, name, features, myWidth, myHeight, isCenter) {
    if (name == '') {
        name = 'yetanotherwindow';
    }
    // Replace evtl. spaces with underscores
    name = name.replace(/ /g, "_");
    if ( (myHeight == '') || (myHeight == 0) ) {
        myHeight = 500;
    }
    if ( (myWidth == '') || (myWidth == 0) ) {
        myWidth = 500;
    }
    if ( (features == "none") || (features == '') ) {
        features = "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes";
    } else if (features == "all") {
        features = "toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes";
    }
    if (window.screen) {
        if ((isCenter != '') && (isCenter != 'false')) {
            var offset =    30;
            var bottom_offset =    70;
            switch (isCenter) {
                case 'top-left':
                    var myLeft = offset;
                    var myTop  = offset;
                break;
                case 'top-right':
                    var myLeft = screen.availWidth - myWidth - offset;
                    var myTop  = offset;
                break;
                case 'top-middle':
                    var myLeft = (screen.availWidth - myWidth) / 2;
                    var myTop  = offset;
                break;
                case 'mid-left':
                    var myLeft = offset;
                    var myTop  = ( (screen.availHeight - myHeight) / 2) - offset;
                break;
                case 'mid-right':
                    var myLeft = (screen.availWidth - myWidth) - offset;
                    var myTop  = ( (screen.availHeight - myHeight) / 2) - offset;
                break;
                case 'bottom-left':
                    var myLeft = offset;
                    var myTop  = screen.availHeight - myHeight - bottom_offset;
                break;
                case 'bottom-middle':
                    var myLeft = (screen.availWidth - myWidth) / 2;
                    var myTop  = screen.availHeight - myHeight - bottom_offset;
                break;
                case 'bottom-right':
                    var myLeft = screen.availWidth - myWidth - offset;
                    var myTop  = screen.availHeight - myHeight - bottom_offset;
                break;
                default:
                    var myLeft = (screen.availWidth - myWidth) / 2;
                    var myTop  = ( (screen.availHeight - myHeight) / 2) - offset;
                break;
            }
            features += (features != '') ? ',' : '';
            features += 'left=' + myLeft + ',top=' + myTop;
        }
    }
    features = (features != '') ? features + ',width=' + myWidth + ',height=' + myHeight : 'width=' + myWidth + ',height=' + myHeight;

    var popupWin = window.open (url, name, features);
    popupWin.focus();
}


/**
 **************************************************************************
 * Function for FAQ
 **************************************************************************
 */
function initFaq() {
    $('#module_faq li h3,#module_faq li a.question').click(function(){
        $(this).parent().find('.answer').slideToggle();
        $(this).parent().toggleClass('opened');

    });
}

/**
 **************************************************************************
 * Function for Pagescrolling
 **************************************************************************
 */
function scrollToAnchor(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}


function initAnchorLink() {
    $('#showWeitereArtikelInfos').click(function(event){
        event.preventDefault();
        // Open the Inhalt tab
        $("#tabInhalt").trigger("click");
        // Go to the tab
        scrollToAnchor("weitereArtikelInfos");
    });

    $('.topLink').click(function(event){
        event.preventDefault();
        scrollToAnchor("top");
    });
}


/**
  **************************************************************************
  * General function for setting default texts
  * uses title attribute
  **************************************************************************
  */

 function checkDefaultTexts(){
    var inputs = $('input[type="text"].defaultText');
    inputs.each(function(i){
        this.value = this.defaultValue = $(this).attr('title');
        $(this).addClass('hasDefaultText');
        $(this).focus(function() {
            if (this.value == this.defaultValue){
                this.value = '';
                $(this).removeClass('hasDefaultText');
            }
            if(this.value != this.defaultValue){
                this.select();
            }
        });
        $(this).blur(function() {
            if ($.trim(this.value) == ''){
                this.value = (this.defaultValue ? this.defaultValue : '');
                $(this).addClass('hasDefaultText');
            }
        });
    });
}


/**
 **************************************************************************
 * Function for Rating
 **************************************************************************
 */
function initRatingDisplay() {
    $('.showRatingLink a').hover(showRating);
    $('.showRatingArrow a').hover(showRating);

    function showRating() {
        $('.ratingAverage').toggleClass('opened');
        $('.showRatingArrow').toggleClass('opened');
        $('.showRatingLink').toggleClass('opened');
        $('.localvisible').toggleClass('opened');
    }
}


/**
 **************************************************************************
 * Function for init of the banner cycles
 **************************************************************************
 */
function initBannerCycle() {
    $('.slideshow').cycle({
        fx:                 'fade',
        nowrap:             true,
        cleartype:          true,
        cleartypeNoBg:      true,
        timeout:            slideShowTime,
        autostop:           true,
        pager:              '#cycleNav ul',
        pagerAnchorBuilder: function(idx, slide) {
            return '#cycleNav li:eq(' + (idx) + ')';
        },
        end: function(options) {
                 $('.slideshow').cycle(0).cycle('pause');
        } // Stop after complete cycle at first image
    });
    $('#cycleNav li').click(function() {
        $('.slideshow').cycle('pause');
    });
    function centerIndicator(){
        $('#cycleNav li').each(function(index) {
            var padding = $(this).find('.a').css('padding', posLeft);
            var posLeft = parseInt($(this).width() + padding)/2 - parseInt($(this).find('.navIndicator').width()/2)
            $(this).find('.navIndicator').css('margin-left', posLeft);
        });
     }
     centerIndicator();
}


/**
 **************************************************************************
 * Function for init of the slider carousels
 **************************************************************************
 */
function initCarousels() {
    $('.jcarousel-skin-thalia-2').jcarousel({
        //visible: 2,
        scroll: 2
    });
    $('.jcarousel-skin-thalia-3').jcarousel({
        visible: 3,
        scroll: 3
    });
    $('.jcarousel-skin-thalia-5').jcarousel({
        visible: 5,
        scroll: 5
    });
    $('.jcarousel-skin-thalia-7').jcarousel({
        visible: 7,
        scroll: 7
    });
    $('div.tabCarousel').hide();
    $('div.tabCarousel:first').show();
    $('div.carouselTabs ul li:first').addClass("first active");
    $('div.carouselTabs ul li a').click(function(event) {
        event.preventDefault();
    });
    $('div.carouselTabs ul li').each(function(){
        $(this).click(function(){
            $('div.carouselTabs ul li').removeClass("active");
            $(this).addClass("active");
            var id = $(this).find('a').attr("rel");
            $('div.tabCarousel').hide();
            $('div#' + id).show();
        });
    });
}


/**
 **************************************************************************
 * Function for showing the "Leseproben St�rer on the article
 * detail page (if a "Leseprobe" exists)
 **************************************************************************
 */
function initLeseprobenStoerer() {
    $("#leseproben_stoerer_image").click(function(){
        // Open the Leseprobe tab
        $("#tabLeseprobe").trigger("click");
        // Go to the tab
        scrollToAnchor("weitereArtikelInfos");
    });
}
function showLeseprobenStoerer() {
    $("#leseproben_stoerer").show();
}

function initShowHoerproben() {
    $("#showHoerproben").click(function(){
        // Open the Hoerproben
        $("#tabHoerprobe").trigger("click");
        // Go to the tab
        scrollToAnchor("weitereArtikelInfos");
    });
    $("#linkHoerprobe").click(function(){
        // Open the Hoerproben
        $("#tabHoerprobe").trigger("click");
        // Go to the tab
        scrollToAnchor("weitereArtikelInfos");
    });
}


/**
 **************************************************************************
 * Function for init Recensions Tab
 **************************************************************************
 */
function initShowRezensionenTab() {
    $("#showTabRecensions").click(function(){
        // Open the Rezensionen
        $("#tabRezensionen").trigger("click");
        // Go to the tab
        scrollToAnchor("weitereArtikelInfos");
    });
}

/**
 **************************************************************************
 * Function for init the video trailerclick
 **************************************************************************
 */
function initVideoTrailer() {
    $("#showTrailer").click(function(){
        // Open the Trailer tab
        $("#tabTrailer").trigger("click");
        // Go to the tab
        scrollToAnchor("weitereArtikelInfos");
    });
}

/**
 **************************************************************************
 * Function for init the image gallery on the article detail page
 **************************************************************************
 */
function initArticleDetailImageGallery() {
    $('a.articleDetailGallery').fancybox({
        speedIn        : 300,
        speedOut       : 150,
        overlayOpacity : 0.8,
        overlayColor   : '#777'
    });
}


/**
 **************************************************************************
 * Function for Article Tabs
 **************************************************************************
 */
function initArticleTabs() {

    if (location.href.indexOf('bewertung') > -1) {
        $('.tabs li').each(function() {
            $(this).removeClass('active');
        });
        $('#tabRezensionen').parents('li').addClass('active');
        $('.tabContent').each(function() {
            $(this).removeClass('active');
        });
        $('#articleRezensionenTab').addClass('active');
    }

    $('.tabsForAdditionalArticleInfo a').click(function(event){
        $('.tabs li').each(function() {
            $(this).removeClass('active');
        });
        $(event.target).parents('li').addClass('active');
        $('.tabContent').each(function() {
            $(this).removeClass('active');
        });
        var tabToShow = event.target.href.substring(event.target.href.indexOf('#')+1);
        $('#' + tabToShow).addClass('active');
        return false;
    });
}

/**
 **************************************************************************
 * Function for Newsletter Tabs
 **************************************************************************
 */
function initNewsletterTabs(){
    $('.tabsForNewsletterSubscribeAndUnsubscribe a').click(function(event){

        $('.tabs li').each(function() {
            $(this).removeClass('active');
        });
        $(event.target).parents('li').addClass('active');

        $('.tabContent').each(function() {
            $(this).removeClass('active');
        });
        var tabToShow = event.target.href.substring(event.target.href.indexOf('#')+1);
        $('#' + tabToShow).addClass('active');

        return false;
    });
}

/**
 **************************************************************************
 * Function for init related articles box
 **************************************************************************
 */
function initRelatedArticles(){
    $('.relatedArticles ul li.active ul').show();

    $('ul.submenu').each(function(index) {
        $(this).find('li:last').css('border-bottom','none');
    });


    $('.relatedArticles ul li a').not('.relatedArticles ul.submenu li a').click(function(event){
        event.preventDefault();

        $('.relatedArticles ul li').removeClass('active');
        $('.relatedArticles ul li ul').hide();

        $(this).parents('li').addClass('active');
        $(this).parents('li').find('ul.submenu').show();
    });
}


/**
 **************************************************************************
 * Function for handling the navigation highlighting for the Geschenkkarte
 **************************************************************************
 */
function handleGeschenkkartenNavigation(action, entry) {
    // Remove the active items
    $("#leftNavCol div.menu ul li").each(function() {
        if ($(this).attr("id")=="menuitem_geschenkkarte_bestellen" ||
            $(this).attr("id")=="menuitem_geschenkkarte_aufladen" ||
            $(this).attr("id")=="menuitem_geschenkkarte_abrufen" ||
            $(this).attr("id")=="menuitem_geschenkkarte_gutschein_bestellen")
        {
                $(this).removeClass("activeItem").addClass("passiveItem");
        }
    });
    if (action=="hightlight") {
        $("#leftNavCol div.menu ul li").each(function() {
            if ($(this).attr("id")==entry) {
                $(this).removeClass("passiveItem").addClass("activeItem");
            }
        });
    }
}


/**
 **************************************************************************
 * Function for collapsible panel
 **************************************************************************
 */
function initCollapsiblePanel(){
    $('.collapsiblePanel .tab h3').click(function(){
        var parentElem = $(this).parents('.panelContainer');
        if (parentElem.hasClass('opened')) {
            parentElem.removeClass('opened').find('.content').slideUp();
            handleGeschenkkartenNavigation('', '');
        } else {
            parentElem.find('.content').slideDown();

            // Special for Geschenkkarte: Show only one open block; therefore we first close all opened blocks and then open the desired one
            $("#module_geschenkkarte div.panelContainer").each(function(){
                if ($(this).hasClass('opened')) {
                    $(this).removeClass("opened").find('.content').slideUp();
                }
            });

            parentElem.addClass('opened');
            handleGeschenkkartenNavigation('hightlight', $(this).attr("class"));
            if ($(this).attr("id")=="geschenkservice") {
                $("#radioUseServiceYes").trigger("click");
            }
        }
    });

    $('.collapsiblePanel .tabHeader input').click(function(){
        var parentElem = $(this).parents('.panelContainer');
        if (!parentElem.hasClass('opened')) {
            $('.panelContainer.opened').removeClass('opened').find('.tabContent').slideUp('fast');
            parentElem.find('.tabContent').slideDown();
            parentElem.addClass('opened');
        }
    });
}

/**
 **************************************************************************
 * Functions for Grusskartentext
 **************************************************************************
 */
function countGrusskartenChars() {
    var gkText = $("#grusstext").val();
    if (gkText.length > maxCharsForGrusskarte) {
        $("#grusstext").val(gkText.substring(0, maxCharsForGrusskarte));
    } else {
        $("#grusstextCounter").html((maxCharsForGrusskarte - gkText.length) + ' Zeichen &uuml;brig');
    }
}
function initGrusskartenCounting() {
    $("#grusstext").keydown(function(){
        countGrusskartenChars();
    });
    $("#grusstext").keyup(function(){
        countGrusskartenChars();
    });
}

/*
**************************************
* activateFlashEmbedding
* embedstring: String containing embed-tags
***************************************
*/
function activateFlashEmbedding(embedstring) {
    document.writeln(embedstring);
}

/**
 **************************************************************************
 * Function for Bookseller List
 **************************************************************************
 */
function initBooksellerList(){
    $('#module_store_bookseller_list li:nth-child(6)').each(function() {
        $(this).addClass('first');
    });
}

/**
 **************************************************************************
 * Functions for the "Bestandsabzeige"
 **************************************************************************
 */
function initBestandsanzeige() {
    $("body").delegate('#bestandsanzeigeLink, #bestandsanzeigeLinkInlayer','click', function(event) {
        event.preventDefault();
        var idOfInputField = $(this).attr("rel");
        var zipOrCity = $("#" + idOfInputField).val();
        var zipOrCityDefault = $("#" + idOfInputField).attr("title");
        if ( (zipOrCity.length < 1) || (zipOrCity == zipOrCityDefault) ) {
            $("#" + idOfInputField + "Error").html("Bitte geben Sie eine PLZ oder einen Ort an!");
            $("#" + idOfInputField).addClass("inputError");
            $("#" + idOfInputField + "Error").show();
        } else {
            var bestandsanzeigeURL = $("#bestandsanzeigeURL").val();
            if ( bestandsanzeigeURL == "") {
                $("#" + idOfInputField + "Error").html("Leider steht die Verf�gbarkeitsabfrage zurzeit nicht zur Verf�gung.");
                $("#" + idOfInputField).addClass("inputError");
                $("#" + idOfInputField + "Error").show();
            } else {
                bestandsanzeigeURL = bestandsanzeigeURL + "&stadt=" + zipOrCity;
                $("#" + idOfInputField + "Error").hide();
                $("#" + idOfInputField).removeClass("inputError");
                $("#" + idOfInputField).val(zipOrCity);
                callBestandsanzeige(bestandsanzeigeURL);
            }
        }
    });
    $('body').delegate('.linkSubmit','keyup',function(e){
        var code = e.which;
        if(code==13){
            e.preventDefault();
            $('#bestandsanzeigeLink').trigger('click');
        }
    });
    $('body').delegate('.linkSubmitLayer','keyup',function(e){
        var code = e.which;
        if(code==13){
            e.preventDefault();
            $('#bestandsanzeigeLinkInlayer').trigger('click');
        }
    });
}
function callBestandsanzeige(bestandsanzeigeURL) {
    $.fancybox.showActivity();
    $.ajax({
        type   : "POST",
        url    : bestandsanzeigeURL,
        success: function(result) {
            $.fancybox.hideActivity();
            $.fancybox(result, {'padding':0});
            $(".stockTable td.tooltip").each(function(){
                $(this).qtip({
                    content: $(this).find(".tooltipContainer"),
                    position: {
                        my: 'left bottom',
                        at: 'right top',
                        target: 'mouse'
                    }
                })
            });
            var trStores = $('.scrollContent .stockTable tbody tr').length;
            var scrollContentHeight = trStores * 45 - 1 + "px";
            if (trStores < 6) {
                $('#module_itemsInStock .scrollContent').css('height', scrollContentHeight);
            }
        }
    });
}


/**
 **************************************************************************
 * Function for event calendar
 **************************************************************************
 */
function eventCalendarInit() {
    // show events for current month
    $('#' + $('.tabNav .selectedTab').attr('id') + "_content").removeClass('hideLayer');

    $('.tabNav .changeTab').click(function() {

        // deactivate all tabs
        $('.tabNav .changeTab').each(function() {
            $(this).removeClass('selectedTab');
            $(this).parents('li').removeClass('active');
        });
        // hide all layers
        $('.detailLayer').each(function() {
            $(this).addClass('hideLayer');
        });
        // activate current tab
        $(this).addClass('selectedTab');
        $(this).parents('li').addClass('active');
        // show current layer
        $('#' + $(this).attr('id') + '_content').removeClass('hideLayer');
        // deactivate all left nav links
        $('.tabNavAlternative .changeTab').each(function() {
            $(this).removeClass('selectedTab');
            $(this).parents('li').removeClass('activeItem');
            $(this).parents('li').addClass('passiveItem');
        });
        // activate current left nav link
        $('.tabNavAlternative #' + $(this).attr('id') + '_link').parents('li').removeClass('passiveItem');
        $('.tabNavAlternative #' + $(this).attr('id') + '_link').parents('li').addClass('activeItem');
        $('.tabNavAlternative #' + $(this).attr('id') + '_link').addClass('selectedTab');

        return false;
    });

    $('.tabNavAlternative a').click(function() {

        // deactivate all left nav links
        $('.tabNavAlternative .changeTab').each(function() {
            $(this).removeClass('selectedTab');
            $(this).parents('li').removeClass('activeItem');
            $(this).parents('li').addClass('passiveItem');
        });
        // hide all layers
        $('.detailLayer').each(function() {
            $(this).addClass('hideLayer');
        });
        // activate current left nav link
        $(this).parents('li').removeClass('passiveItem');
        $(this).parents('li').addClass('activeItem');
        $(this).addClass('selectedTab');
        // show current layer
        $('#' + $(this).attr('id').substr(0, $(this).attr('id').indexOf('_link')) + '_content').removeClass('hideLayer');
        // deactivate all tabs
        $('.tabNav .changeTab').each(function() {
            $(this).removeClass('selectedTab');
            $(this).parents('li').removeClass('active');
        });
        // activate current tab
        $('.tabNav #' + $(this).attr('id').substr(0, $(this).attr('id').indexOf('_link'))).addClass('selectedTab');
        $('.tabNav #' + $(this).attr('id').substr(0, $(this).attr('id').indexOf('_link'))).parents('li').addClass('active');

        return false;
    });
}


/**
 **************************************************************************
 * Function for initialisation of the filial detail page
 **************************************************************************
 */
function initFilialDetailPage() {
    $("a.filialeGallery").fancybox({
        'speedIn'        : 300,
        'speedOut'       : 150,
        'overlayOpacity' : 0.8,
        'overlayColor'   : '#777'
    });
    $("#showFilialGallery").click(function(event){
        event.preventDefault();
        $("#firstImage").trigger('click');
    });
    if ( $(".filialenliste li").length > 5 ) {
        $(".filialenliste li").each(function(i){
            if (i>5) {
                $(this).hide();
            }
        });
        $("#showAllFilialen").show();
    } else {
        $("#showAllFilialen").hide();

    }
    $("#showAllFilialen").click(function(event){
        event.preventDefault();
        $(".filialenliste li").each(function(i){
            $(this).show();
        });
        $(this).hide();
    });
}

/**
 **************************************************************************
 * Function for initialisation of Input Hover Buttons
 **************************************************************************
 */
function initInputHoverBtns() {
    $('.inputHoverBtn').each(function(){
         imgURL = $(this).attr('src');
         imgHoverURL = imgURL.substr(0,imgURL.length-4)+'_mo.gif';

         $(this).mouseover(function(){
            $(this).attr('src',imgHoverURL);
         });

         $(this).mouseout(function(){
            $(this).attr('src',imgURL);
         });
    });
}

/**
 **************************************************************************
 * Function to validate an email address (only syntactical check)
 **************************************************************************
 */
function checkEmail(email) {
    var filter  = /^([a-zA-Z0-9]){1}([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return filter.test(email);
}

/**
 **************************************************************************
 * Function to redirect to a given URL
 **************************************************************************
 */
function redirectToPage(url) {
    window.location.href = url;
}

function initGKFormularEnterKeys() {
    $('#ordercard #ID_gutscheinwert').keyup(function(e){
        var code = e.which;
        if(code==13){
            e.preventDefault();
            $('input[name="bestellen"]').trigger("click");
            return false;
        }
    });
    $('#loadcard #ID_gutscheinwert, #loadcard #giftCardNo, #loadcard #pin').keyup(function(e){
        var code = e.which;
        if(code==13){
            e.preventDefault();
            $('input[name="aufladen"]').trigger("click");
            return false;
        }
    });
    $('#showamount #giftCardNo, #showamount #pin').keyup(function(e){
        var code = e.which;
        if(code==13){
            e.preventDefault();
            $('input[name="abrufen"]').trigger("click");
            return false;
        }
    });
}


function initEbookSpecial() {

    $(".ebookTooltip").each(function(){
        $(this).qtip({
            content: $('#' + $(this).attr('rel')).html(),
            position: {
                my: 'right top',
                at: 'left bottom',
                target: 'event'
            },
            style: {
                classes: 'ebookSpecial'
            }
        })
    });

    $(".showBestellenAndDownloadenLayer").each(function(){
        $(this).click(function (e){
            e.preventDefault();
            showBestellenAndDownloadenLayer();
        });
    });
}

/**
 **************************************************************************
 * Function for the info layer on the ebook article detail page
 **************************************************************************
 */
function showBestellenAndDownloadenLayer() {
    $.fancybox({
        content        : $("#ebookBestellenAndDownloadenContainer").html(),
        speedIn        : 300,
        speedOut       : 150,
        overlayOpacity : 0.8,
        overlayColor   : '#777',
        padding        : 0
    });
}

 /**
  **************************************************************************
  * Function to show the xmas layer after page load
  * (only if the corresponding cookie is not set)
  * Furthermore we check if a success or failre layer should be displayed
  **************************************************************************
  */
 var hasBmResult = false;
 var bmResult = '';
 function checkForBmResult() {
     if (window.location.search != "") {
         var tmp, parameter;
         var pairs = new Array();
         var names = new Array();
         var values = new Array();
         var search = window.location.search;
         if (search.indexOf("bmResult")>-1) {
             parameter = unescape(search);
             parameter = parameter.substr(1,parameter.length);
             pairs = parameter.split("&");
             for (i=0; i<pairs.length; i++) {
                 tmp = pairs[i].split("=");
                 names[i]  = unescape(tmp[0]);
                 values[i] = unescape(tmp[1]);
                 if (names[i] == "bmResult") {
                     hasBmResult = true;
                     bmResult = values[i].toLowerCase();
                 }
             }
         }
     }
 }


 var xmasLayeroverlayOpacity = 0.3;
 function showXmasLayer() {
     $.fancybox({
         'href'           : '#newsletter_xmas_layer',
         'padding'        : 1,
         'width'          : 727,
         'height'         : 339,
         'speedIn'        : 300,
         'speedOut'       : 150,
         'overlayOpacity' : xmasLayeroverlayOpacity,
         'overlayColor'   : '#000'
     });
 }
 function showXmasSuccessLayer() {
     $("#newsletter_xmas_opener_success").fancybox({
         'padding'        : 1,
         'width'          : 727,
         'height'         : 339,
         'speedIn'        : 300,
         'speedOut'       : 150,
         'overlayOpacity' : xmasLayeroverlayOpacity,
         'overlayColor'   : '#000'
     });
     $("#newsletter_xmas_opener_success").click();
 }
 function showXmasFailureLayer() {
     $("#newsletter_xmas_opener_failure").fancybox({
         'padding'        : 1,
         'width'          : 727,
         'height'         : 339,
         'speedIn'        : 300,
         'speedOut'       : 150,
         'overlayOpacity' : xmasLayeroverlayOpacity,
         'overlayColor'   : '#000'
     });
     $("#newsletter_xmas_opener_failure").click();
 }
 function showXmasBlacklistedLayer() {
     $("#newsletter_xmas_opener_blacklisted").fancybox({
         'padding'        : 1,
         'width'          : 727,
         'height'         : 339,
         'speedIn'        : 300,
         'speedOut'       : 150,
         'overlayOpacity' : xmasLayeroverlayOpacity,
         'overlayColor'   : '#000'
     });
     $("#newsletter_xmas_opener_blacklisted").click();
 }
 function showXmasDuplicateLayer() {
     $("#newsletter_xmas_opener_duplicate").fancybox({
         'padding'        : 1,
         'width'          : 727,
         'height'         : 339,
         'speedIn'        : 300,
         'speedOut'       : 150,
         'overlayOpacity' : xmasLayeroverlayOpacity,
         'overlayColor'   : '#000'
     });
     $("#newsletter_xmas_opener_duplicate").click();
 }


 /**
  **************************************************************************
  * Function to check the xmas newsletter layer form
  **************************************************************************
  */
 function checkNewsletterXmasForm() {
     var formError = false;
     var email = $("#newsletter_xmas_email").val();
     $("div.newsletter_xmas_email_input").removeClass("xmasError");
     if ( !checkEmail(email) ) {
         formError = true;
         $("div.newsletter_xmas_email_input").addClass("xmasError");
     }
     if (formError) {
         $("#xmasHeadline").css("margin-bottom", "10px");
         $("#newsletter_xmas_form_error").show();
         return false;
     } else {
         var successURL = 'http%3A%2F%2Ftst.buch.de%2Fde.buch.shop%2Fshop%2F2%2Ftha_homestartseite%2Fshow%2F';
         var failureURL = 'http%3A%2F%2Ftst.buch.de%2Fde.buch.shop%2Fshop%2F2%2Ftha_homestartseite%2Fshow%2F';
         if ( location.href.indexOf("http://tst.buch") <= -1 ) {
             successURL = 'http%3A%2F%2Fwww.thalia.de%2Fshop%2Ftha_homestartseite%2Fshow%2F';
             failureURL = 'http%3A%2F%2Fwww.thalia.de%2Fshop%2Ftha_homestartseite%2Fshow%2F';
         }
         var optivoURL  = 'https://api.broadmail.de/http/form/IKYLQD-IL1JAH-N80V08/subscribe';
         optivoURL     += '?bmOverwrite=false';
         optivoURL     += '&bmSuccessUrl=' + successURL;
         optivoURL     += '&bmFailureUrl=' + failureURL;
         optivoURL     += '&bmRecipientId=' + email;
         optivoURL     += '&bmOptInId=4057845379';
         optivoURL     += '&affiliate=gewinnspiel_xmas11';
         document.location.href = optivoURL;
         return false;
     }
 }


 /**
  **************************************************************************
  * Function to initialize the xmas newsletter layer
  **************************************************************************
  */
 function initXmasNewsletter() {
     // Remember: Month counter starts at 0 !
     var endZeit      = new Date(2012, 6, 27, 0, 0, 1);
     var aktuelleZeit = new Date();
     if (aktuelleZeit<=endZeit) {
         $('#newsletter_xmas_email').keyup(function(e){
             var code = e.which;
             if(code==13){
                 e.preventDefault();
                 checkNewsletterXmasForm();
             }
         });
         checkForBmResult();
         if (hasBmResult) {
             $.setCookie("newsletterLead", "yes");
             switch(bmResult) {
                 case 'ok':
                     showXmasSuccessLayer();
                     break;
                 case 'duplicate':
                     showXmasDuplicateLayer();
                     break;
                 case 'blacklisted':
                     showXmasBlacklistedLayer();
                     break;
                 default:
                     showXmasFailureLayer();
                     break;
             }
         } else {
             //if (!$.getCookie("newsletterLead")) {
              //   $.setCookie("newsletterLead", "yes");
                 showXmasLayer();
             //}
         }

         $("#teilnehmen_link").click(function(event){
             event.preventDefault();
             checkNewsletterXmasForm();
         });

         $("#jetzt_shoppen_link, #nicht_teilnehmen_link").click(function(event){
             event.preventDefault();
             $.fancybox.close();
         });

         $("#mit_anderer_adresse_teilnehmen_link").click(function(event){
             event.preventDefault();
             showXmasLayer();
         });

         $("#newsletter_xmas_teilnahmebedingungen_link").click(function(){
             $("#newsletter_xmas_teilnahmebedingungen").show();
         });

         $("#newsletter_xmas_teilnahmebedingungen_close").click(function(){
             $("#newsletter_xmas_teilnahmebedingungen").hide();
         });
     }

 }
 
 
/**
 **************************************************************************
 * Functions etc. to be called after the DOM is ready ...
 **************************************************************************
 */
$(function(){
    // Initialization of main navigation
    initMainNav();

    // Initialization of hovering the cover element in a slider
    hoverCover();

    // Initialization for the rating stars layer
    initRatingDisplay();

    // Initialization for the default texts for various input fields
    checkDefaultTexts();

    // Initialization Search Filter View
    $('#sswg').selectbox();

    // Initialization for the leseproben st�rer functionality
    initLeseprobenStoerer();

    // Initialization of the "Weitere ArtikeliInfos" link
    initAnchorLink();

    // Initialization of accordion functionality
    initCollapsiblePanel();

    // Initialization of the "grusskarten counting"
    initGrusskartenCounting();

    // Initialization of newsletter tabs
    initNewsletterTabs();

    // Initialization of the FAQ
    initFaq();

    // Initialization of the Bestandsanzeige
    initBestandsanzeige();

    // Initialization of the bookseller list
    initBooksellerList();

    // Initialization of the event calendar
    eventCalendarInit();

    // Init Input Hover Buttons
    initInputHoverBtns();

    // Init enter keys on the GK page
    initGKFormularEnterKeys();

    // Init ebooks qtipp functionality
    initEbookSpecial();

});

