var MAINTEASER_DATA = {
    // height of one button
    'buttonHeight': 61,
    // duration of the fade over animation
    'animationDuration': 800,
    // is there currently an animation?
    'animationState': 0,
    // is there currently a fade?
    'fadeState': 0,
    // currently highlighted button, if any
    'highlightedButton': -1,
    // which button is the first one visible?
    'buttonBoxOffset': 0,
    // holds the interval which changes the buttons from time to time
    'interval': -1,
    // [preloader] how many images are loaded?
    'imagesLoaded': 0
};

/**
 * Highlights a certain button and displays new content. Usually called when
 * a button is clicked.
 */
function clickButton(i, noScroll)
{
    // if the button is already highlighted, go to the appropriate url
    if (MAINTEASER_DATA.highlightedButton == i) {
        teaserClick();
    }

    // if something is fading, ignore the event
    if (MAINTEASER_DATA.fadeState != 0) {
        return false;
    }

    // reset the interval
    if (MAINTEASER_DATA.interval != -1) {
        clearInterval(MAINTEASER_DATA.interval);
        startInterval();
    }

    // reset the old highlighted button
    if (MAINTEASER_DATA.highlightedButton != -1) {
        $('#MainTeaserButtons .buttonBox .button:eq(' + MAINTEASER_DATA.highlightedButton + ')').removeClass('buttonHighlight');
        // fix for ie, also change class of the button in the second buttonBox
        $('#MainTeaserButtons .buttonBox:eq(1) .button:eq(' + MAINTEASER_DATA.highlightedButton + ')').removeClass('buttonHighlight');
    }

    // highlight the new button
    MAINTEASER_DATA.highlightedButton = i;
    $('#MainTeaserButtons .buttonBox .button:eq(' + i + ')').addClass('buttonHighlight');
    // fix for ie (actually the previous line should select the first button in
    // ALL button boxes, not just the first one)
    $('#MainTeaserButtons .buttonBox:eq(1) .button:eq(' + i + ')').addClass('buttonHighlight');

    // maybe we need to move the button box?
    if (MAINTEASER_GAMES.length > 4 && (typeof(noScroll) == "undefined" || !noScroll)) {
        if (MAINTEASER_DATA.buttonBoxOffset == i) {
            // is the first button highlighted?
            moveButtons(1);
        } else if (normalizeOffset(MAINTEASER_DATA.buttonBoxOffset + 3) == i) {
            // is the last button highlighted?
            moveButtons(-1);
        }
    }

    // start fading
    MAINTEASER_DATA.fadeState = 1;

    // new image, fade the overlay in, fade the base element out
    $('#MainTeaserImage .overlay').hide();
    $('#MainTeaserImage .overlay').css('background-image', 'url(' + MAINTEASER_GAMES[i].image + ')');
    $('#MainTeaserImage .overlay').fadeIn(
        MAINTEASER_DATA.animationDuration,
        function() {
            $('#MainTeaserImage').css('background-image', 'url(' + MAINTEASER_GAMES[i].image + ')');
            MAINTEASER_DATA.fadeState = 0; // reset fade state
        }
    );

    // new texts
    fadeText('#MainTeaserTitle', MAINTEASER_GAMES[i].title);

    // if there is a strike price, the price field has to be wider
    var c = '';
    if (MAINTEASER_GAMES[i].has_strike_price == 1) {
        c = ' Wide';
    }

    var t = '<div class="Text' + c + '">' + MAINTEASER_GAMES[i].text + '</div><div class="Price' + c + '">' + MAINTEASER_GAMES[i].price + '</div>';
    fadeText('#MainTeaserText', t);

}

/**
 * Reads the config array, creates the buttons and highlights the first one.
 * Starts the interval which scrolls the button box,
 */
function doinit()
{
    // create buttons
    for (var i in MAINTEASER_GAMES) {
        var label = MAINTEASER_GAMES[i].button_label;
        if (label == "") {
            label = MAINTEASER_GAMES[i].title;
        }

        $('<div class="button" onclick="clickButton(' + i + ')"><div class="area colored' + MAINTEASER_GAMES[i].color + '">' + MAINTEASER_GAMES[i].area + '</div><div class="title">' + label + '</div></div>').appendTo('.buttonBox');
    }

    // maybe hide the next/prev buttons?
    if (MAINTEASER_GAMES.length <= 4) {
        $('#MainTeaserButtonPrev').css('visibility', 'hidden');
        $('#MainTeaserButtonNext').css('visibility', 'hidden');
    }

    // duplicate it for scolling
    if (MAINTEASER_GAMES.length >= 4) {
        $('#MainTeaserButtons .buttonBox').clone().appendTo('#MainTeaserButtons');
    }

    // ie6 fixes
    if (jQuery.browser.msie && jQuery.browser.version <= 6) {
        // hover fix
        $('.MainTeaserBox .button').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
        $('#MainTeaserButtonPrev').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
        $('#MainTeaserButtonNext').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });

    }

    // ie8 claims to be ie7 in compatibility mode, so check for Trident/4.0 as well
//     if (jQuery.browser.msie && jQuery.browser.version <= 7) {
        // background-color to fix ie bug, see http://www.kevinleary.net/jquery-fadein-fadeout-problems-in-internet-explorer/
//         $('#MainTeaserTitle .overlay').css('background-color', '#eee');
//         $('#MainTeaserText .overlay').css('background-color', '#fff');
//         $('#MainTeaserPrice .overlay').css('background-color', '#fff');
//     }

    // highlight first button
    clickButton(0, true);
    startInterval();
}

/**
 * Fades the "go" button in and out, depending on given opacity.
 */
function fadeButton(opacity)
{
    $('#MainTeaserGo').stop();
    $('#MainTeaserGo').fadeTo(1000, opacity);
}

/**
 * Fades some text for a certain element. That element has to contain two divs,
 * each with class "overlay".
 *
 * @param string element jQuery selector, for example ".title".
 * @param string html New HTML content.
 */
function fadeText(element, html)
{
    // apply the html to the overlay, but hide it at first
    $(element + ' .overlay:eq(1)').css('opacity', 0);
    $(element + ' .overlay:eq(1)').html(html);



    // start the animation, fade the base element out, fade the overlay in
    $(element + ' .overlay:eq(0)').animate(
        {'opacity': 0},
        MAINTEASER_DATA.animationDuration
    );

    $(element + ' .overlay:eq(1)').animate(
        {'opacity': 0.85},
        MAINTEASER_DATA.animationDuration,
        'swing',
        function() {
            $(element + ' .overlay:eq(0)').html(html); // apply the html to the base element
            $(element + ' .overlay:eq(0)').css('opacity', 0.85); // show it
            $(element + ' .overlay:eq(1)').css('opacity', 0); // hide the overlay
        }
    );


}

/**
 * Highlights the next button.
 */
function highlightNextButton()
{
    if (MAINTEASER_DATA.animationState != 0) {
        return false;
    }
    clickButton(normalizeOffset(MAINTEASER_DATA.highlightedButton + 1));
}

/**
 * Move the buttons up or down.
 *
 * @param int direction 1 means down, -1 means up.
 */
function moveButtons(direction)
{
    // maybe it is already moving? then we do nothing
    if (MAINTEASER_DATA.animationState == 1) {
        return false;
    }

    // compute new position
    var t = $('#MainTeaserButtons .buttonBox').css('top');
    t = parseInt(t.substring(0, t.length - 2)); // remove "px"

    var buttonHeight = MAINTEASER_DATA.buttonHeight;

    // the new top is too high? then we move the both buttonBoxes down one full length
    if (t + direction * buttonHeight > 0) {
        t -= MAINTEASER_GAMES.length * buttonHeight;
        $('#MainTeaserButtons .buttonBox').css('top', t + 'px');
    }
    // if the new position is too low, we move the both buttonBoxes up
    if (t + direction * buttonHeight < -1 * MAINTEASER_GAMES.length * buttonHeight) {
        t += MAINTEASER_GAMES.length * buttonHeight;
        $('#MainTeaserButtons .buttonBox').css('top', t + 'px');
    }

    // save offset
    MAINTEASER_DATA.buttonBoxOffset = normalizeOffset(MAINTEASER_DATA.buttonBoxOffset - direction);

    // animate
    MAINTEASER_DATA.animationState = 1;
    $('#MainTeaserButtons .buttonBox').animate(
        {'top': (t + direction * buttonHeight) + 'px'},
        MAINTEASER_DATA.animationDuration, function() {
            MAINTEASER_DATA.animationState = 0; // reset animation state
        }
    );
}

/**
 * Keep offset between 0 and MAINTEASER_GAMES.length (and not for example -1)
 */
function normalizeOffset(i)
{
    return ((i + MAINTEASER_GAMES.length) % MAINTEASER_GAMES.length);
}

/**
 * Reads the config array and preloads all images. When this is done, call doInit().
 */
function preload()
{
    var cache = [];
    MAINTEASER_DATA.imagesLoaded = 0;
    for (var i = MAINTEASER_GAMES.length; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.onload = function() {
            MAINTEASER_DATA.imagesLoaded++;
            if (MAINTEASER_DATA.imagesLoaded >= MAINTEASER_GAMES.length) { doinit(); }
        };
        cacheImage.src = MAINTEASER_GAMES[i].image;
        cache.push(cacheImage);
    }
}

/**
 * Start the interval, which cycles throuth the button list.
 */
function startInterval()
{
    MAINTEASER_DATA.interval = setInterval('highlightNextButton()', 4000);
}

/**
 * This is called when the user clicks on the image. Changes location
 * to the url of the currently active button.
 */
function teaserClick()
{
    var url = MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].link;

    // ati track
    if (typeof(MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].track_campaign) != 'undefined') {
        if (url.indexOf(':') == -1)
            url = location.protocol + '//' + location.host + url;
        url = xtsd + '.xiti.com/go.ad?xts=' + xtsite + '&atc=' + MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].track_campaign + '&type=AT&url=' + url;
    }
    xt_med('F', ATI_LEVEL2, MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].track_name);

    if (MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].area == 'freegames') {
        window.open(url, 'online_spielen_1', 'width=' + MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].popup_width + ',height=' + MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].popup_height + ',top=20,left=20,scrollbars=yes,resizable=no');
    } else if (MAINTEASER_GAMES[MAINTEASER_DATA.highlightedButton].target == '_blank') {
        window.open(url, '_blank', 'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
    } else {
        location.href = url;
    }
}



/**
 * Erstellt die Flashbox bzw. versieht sie mit Funktionalitaet
 *
 * @author SD
 * @param object options Konfiguration der Box, Optionen siehe Standardeinstellungen
 */
(function($) {
    $.fn.teaserFlashBox = function(options) {
        return this.each(function() {
            //Standardeinstellungen
            var o = $.extend({
                autoplay: true,
                autoplayInterval: 4000,
                effectDuration: 500
            }, options);

            //Basisvariablen
            var box = $(this);
            var backgrounds = box.find(".content_image .content");
            var items = box.find(".content_teaserbar .teaser");
            var activeitem = 0;

            //Initialisierungsfunktion
            var init = function() {
                //Einzelne Eintrage verarbeiten
                items.each(function() {
                    var item = $(this);
                    item.click(function(){
                        //automatisches Abspielen
                        o.autoplay = false;

                        //Bild austauschen
                        activeitem = parseInt(item.attr("data-number"));
                        var oldbackground = backgrounds.filter(".active");
                        var newbackground = backgrounds.eq(activeitem);

                        //Wenn schon aktiv
                        if (newbackground.hasClass("active")) {
                            //Den Link aufrufen
                            navigate();
                            return false;
                        }

                        //Neuen Hintergrund als aktiv markieren
                        newbackground.addClass("active");
                        //Reihenfolge der Hintergruende festlegen
                        backgrounds.css("z-index", 1);
                        oldbackground.css("z-index", 2);

                        //Alle nicht-aktiven Hintergruende ausblenden
                        backgrounds.filter(":not(.active)").css("opacity", "0");
                        backgrounds.filter(".active").css("opacity", "1");

                        //Alten Hintergrund ausfaden und deaktivieren
                        oldbackground.stop(true, true).animate({"opacity": 0}, o.effectDuration);
                        oldbackground.removeClass("active");

                        //Alle Eintraege als inaktiv markieren
                        items.removeClass("active");

                        //Ausgewaehlten Eintraege als inaktiv markieren
                        item.addClass("active");

                        //Verhindern, dass der Link aufgerufen wird
                        return false;
                    });
                });

                //Hintergrundgrafik mit Funktion versehen
                if($('.flashbox_border').length>0){
                //wenn Rahmen die Bilder ueberlagert, muss das Clickevent an
                //den Rahmen gehaengt werden
                  $('.flashbox_border').click(function() {

                      //Aktiven Eintrag finden
                      var item = items.filter(".active");

                      //Click-Event ausloesen und ggf. Navigation durchfuehren
                      navigate();

                      return true;
                  });
                }
                //das Ding hier muss immer ausgefuehrt werden, da der IE die
                //Clickfunktion nicht auf $('.flashbox_border') legt...
                backgrounds.click(function() {
                    //Aktiven Eintrag finden
                    var item = items.filter(".active");

                    //Click-Event ausloesen und ggf. Navigation durchfuehren
                    navigate();

                    return true;
                });

                //Ersten Eintrag als aktiv markieren
                items.eq(0).addClass("active");
                backgrounds.css("visibility", "visible");
                backgrounds.css("opacity", "0");
                backgrounds.eq(0).css("opacity", "1");
                backgrounds.eq(0).addClass("active");

                window.setTimeout(next, o.autoplayInterval);
            }

            //Wechsel zum naechsten Eintrag
            var next = function() {
                if (!o.autoplay)
                    return;

                //Klick auf den naechsten Knopf simulieren
                items.eq((activeitem + 1) % items.length).click();
                o.autoplay = true;

                //Sich selbst nach der angegebenen Zeit wieder aufrufen
                window.setTimeout(next, o.autoplayInterval);
            }

            //Oeffnet einen Link und fuehrt das Tracking durch
            var navigate = function() {
                //Eintraglink suchen
                var itemlink = items.filter(".active").find("a.link");
                var url = itemlink.attr("href");

                // ATI-Kampagnen-Tracking hinzufuegen
                if (url.indexOf(':') == -1)
                    url = location.protocol + '//' + location.host + url;
                url = xtsd + '.xiti.com/go.ad?xts=' + xtsite + '&atc=' + itemlink.attr("data-campaign") + '&type=AT&url=' + url;

                //Klick tracken
                xt_med('F', ATI_LEVEL2, itemlink.attr("data-name"));

                //Schauen, ob der Link in einem Popup, neuen Fenster oder normal geöffnet werden soll
                if (itemlink.attr("data-popup") == "1") {
                    window.open(url, 'online_spielen_1', 'width=' + itemlink.attr("data-width") + ',height=' + itemlink.attr("data-height") + ',top=20,left=20,scrollbars=yes,resizable=no');
                } else if (itemlink.attr("target") == '_blank') {
                    window.open(url);
                } else {
                    window.location.href = url;
                }
            }

            init();
        });
    }
})(jQuery);

var initialized = false;
jQuery(function(){
    if (!initialized) {
        //Flash-Box initialisieren
        jQuery(".flashbox").teaserFlashBox();

        //Breite der Tabs der Tab-Box anpassen
        (function($) {
            $('.tabbox_head').each(function() {
                var box = $(this);
                var items = box.find("li.nav");
                var width = 0;
                //Gesamtbreite der Tabs berechnen
                items.each(function() {
                    var item = $(this);
                    //Den Texten eine ganzzahlige Breite verpassen, damit im IE keine Rundungsprobleme auftreten
                    var textWidth = Math.ceil(item.find(".text").width() + .5);
                    item.find(".text").width(textWidth);
                    width += item.width();
                });
                var pos = 0;
                var diff = box.width() - width;// + (document.all ? -1 : 0);
                //Solange Pixel verteilen bis die Tabs die komplette Breite einnehmen
                while (pos < diff && diff > 0) {
                    if (pos % 2 == 0) { // Pos ist gerade: Pixel nach links
                        var itemno = (pos / 2) % items.length;
                        items.eq(itemno).find(".text").css("padding-left", (parseInt(items.eq(itemno).find(".text").css("padding-left").replace("px","")) + 1) + "px");
                    } else { // Pos ist ungerade: Pixel nach rechts
                        var itemno = ((pos - 1) / 2) % items.length;
                        items.eq(itemno).find(".text").css("padding-right", (parseInt(items.eq(itemno).find(".text").css("padding-right").replace("px","")) + 1) + "px");
                    }
                    pos++;
                }
            });
        })(jQuery)
    }
    initialized = true;
});

