/*global dotLBInitialize, $, window, txGlossary, alert*/

// TODO: refactor
if (typeof dotLBInitialize === "undefined") {

    var trans = (function () {
        // private
        var tooltip = "<div class='tooltip hidden'><div></div></div>",
            moveInterval = 175,
            questionTimeout,

            getPosition = function (node) {
                var x = 0,
                    y = 0;
                do {
                    x += node.offsetLeft;
                    y += node.offsetTop;
                } while ((node = node.offsetParent));

                return {
                    x: x,
                    y: y
                };
            };

        // public
        return {
            contentNode: $("#content"),

            // TODO: use a plugin
            tooltip: function () {
                var text = $(this).attr("sltitle"),
                    tooltipheight;

                if (questionTimeout) {
                    clearTimeout(questionTimeout);
                }

                if (typeof tooltip === "string") {
                    tooltip = $("div#page").after(tooltip).next();
                    tooltip.mouseover(function () {
                        if (questionTimeout) {
                            clearTimeout(questionTimeout);
                        }
                    }).mouseout(function () {
                        trans.setQuestionTimeout();
                    });
                }

                tooltip.stop(true)
                        .addClass("hidden")
                        .removeAttr("style");

                if (text) {
                    tooltip.children("div").html(text);

                    if ($(this).hasClass("question")) {
                        (function () {
                            var questionNode = $("div.homepage-specials"),
                                position = getPosition(questionNode.get(0));

                            tooltip
                                    .removeClass("tooltip-glossar")
                                    .addClass("tooltip-question")
                                    .css("left", position.x + questionNode.width() /
                                            2 - tooltip.width() / 2 + "px")
                                    .css("top", position.y - tooltip.height() - 10 + "px")
                                    .removeClass("hidden");
                        }());
                    } else if ($(this).hasClass("glossar")) {

                        tooltip
                                .addClass("tooltip-glossar")
                                .removeClass("tooltip-question")
                                .removeClass("tooltip-rudimental");
                        tooltipheight = tooltip.height();
                        $(this).mousemove(function (e) {
                            var x = e.pageX - 20,
                                y = e.pageY + 20,
                                windowwidth = $(window).width(),
                                windowheight = $(window).height();

                            if (windowwidth && windowwidth < x + 320) {
                                x -= 230;
                                tooltip.addClass("tooltip-rudimental");
                            }

                            if (tooltipheight && windowheight &&
                                    windowheight < y + tooltipheight + 50) {
                                y -= tooltipheight + 50;
                                tooltip.addClass("tooltip-rudimental");
                            }

                            tooltip
                                    .css("left", x + "px")
                                    .css("top", y + "px")
                                    .removeClass("hidden");
                        });
                    }
                }
            },

            extooltip: function (tooltipType) {
                if (typeof tooltip !== "string") {
                    tooltip.hide("fast", function () {
                        tooltip.addClass("hidden").removeAttr("style");
                    });
                }
            },

            setQuestionTimeout: function () {
                if (questionTimeout) {
                    clearTimeout(questionTimeout);
                }
                questionTimeout = setTimeout(function () {
                    trans.extooltip("tooltip-question");
                }, 3000);
            },

            toogleMetaInfo: function () {
                $(".text-content .meta-info .headline", trans.contentNode)
                        .toggleClass("open")
                        .toggleClass("closed")
                        
                        .next()
                        .slideToggle();
            },

            loadOverview: function () {
                var overviewUrl = $(this).attr("href");
                if (!$(".text-content div.overview", trans.contentNode).length) {
                    $(".text-content", trans.contentNode)
                            .append('<div class="overview hidden"></div>')
                            .find("div.overview")
                            .load(overviewUrl, function () {
                        $(this).children("div.text")
                                .append('<a class="button close"><span>Etappen&uuml;bersicht ' +
                                'schlie&szlig;en</span></a>');
                        trans.toggleOverview();
                    });
                } else {
                    trans.toggleOverview();
                }

                return false;
            },

            toggleOverview: function () {
                $(".text-content div.overview, .text-content div.step", trans.contentNode)
                        .slideToggle();
                return false;
            },

            moveLeft: function () {
                var ulContainer = $(".gallery .slide-container ul", trans.contentNode),
                    newMargin = parseInt(ulContainer.css("margin-left"), 10) + (moveInterval * 3);

                newMargin = newMargin > 0 ? 0 : newMargin;
                ulContainer.stop().animate({
                    marginLeft: newMargin + "px"
                }, 1000, "swing");
            },

            moveRight: function () {
                //Check the length of the slide-container
                var containerLength = $(".gallery .slide-container ul li", trans.contentNode)
                        .length * moveInterval,
                    ulContainer = $(".gallery .slide-container ul", trans.contentNode),
                    newMargin = parseInt(ulContainer.css("margin-left"), 10) - (moveInterval * 3),
                    minMargin = -containerLength + 5 * moveInterval,
                    width = $(".gallery .slide-container", trans.contentNode).width();

                if (containerLength > width) {
                    ulContainer.css("width", containerLength + "px").stop().animate({
                        marginLeft: newMargin < minMargin ? minMargin : newMargin + "px"
                    }, 1000, "swing");
                }
            },

            // equalizes height of content and sidebar, should be called after trans.arrangeTeasers
            alignLeftRightContent: function () {
                var left = $("div.teaser-content-left, div.text-content-left", trans.contentNode),
                    right = $("div.teaser-content-right, div.text-content-right",
                            trans.contentNode),
                    both = left.add(right);
                both.height(
                Math.max(
                left.height(), right.height()) + "px");
            },

            // equalizes heights of two neighboring teasers
            arrangeTeasers: function () {
                var teaser = $(".unified-teaser:not(.main-unified-teaser), .big-teaser"),
                    i = 0,
                    k = teaser.length - 1;
                for (; i < k; i += 2) {
                    // .add creates a tmp nodelist of .eq(i) and .eq(i + 1)
                    teaser.eq(i).add(teaser.eq(i + 1)).height(
                    Math.max(
                    teaser.eq(i).height(), teaser.eq(i + 1).height()) + "px");
                }
                teaser.removeClass("hidden");
            },

            // TODO: refactor this, see http://www.ueberleben-mit-brustkrebs.de/
            renderGlossary: function () { // searchs side for glossary entries
                if (/glossar\.html$/.test(location.pathname) || typeof txGlossary === "undefined" ||
                        !txGlossary) {
                    return;
                }
                var node, text, reqex, newText;

                node = $(".text-content div.text");
                node = !node.length ? $(".text-content-left") : node;
                node = !node.length ? $(".text-content") : node;
                node = !node.length ? $(".teaser-content .teaser .text") : node;

                if (node.length) {
                    node.each(function (n) {
                        text = node.eq(n).html();
                        if (text) {
                            for (var key in txGlossary) {
                                if (txGlossary.hasOwnProperty(key)) {
                                    try {
                                        reqex = new RegExp(["(>[^<]*)(", key, ")"].join(""));
                                        newText = ["$1", '<span class="glossar" sltitle="',
                                                txGlossary[key], '">', "$2", '</span>'].join("");
                                        text = text.replace(reqex, newText);
                                    } catch(error) {
                                    }
                                }
                            }
                            node.eq(n).html(text);
                            //Re-Bind tooltip
                            $("span.glossar, a.question")
                                    .mouseover(trans.tooltip)
                                    .mouseout(trans.extooltip);
                        }
                    });
                }
            },

            placeZoom: function (zoom) {
                zoom = zoom || $("a.thickbox[href$='jpg'], a.thickbox[href$='jpeg'], " +
                        "a.thickbox[href$='gif'], a.thickbox[href$='png']")
                        .append('<div class="zoomwrap"><img src="/_global/images/zoom.png" alt=""' +
                        ' class="zoom" /></div>').find("img.zoom");
                return zoom;
            }
        };
    }());

    $("span.glossar, a.question").mouseover(trans.tooltip);
    $("span.glossar").mouseout(trans.extooltip);
    $("a.question").mouseout(trans.setQuestionTimeout);

    $(".text-content a.overview", trans.contentNode).live("click", trans.loadOverview);

    $(".text-content a.close", trans.contentNode).live("click", trans.toggleOverview);

    $(".text-content .meta-info .headline", trans.contentNode)
            .live("click", trans.toogleMetaInfo);

    $(".gallery .slider-left", trans.contentNode).click(trans.moveLeft);

    $(".gallery .slider-right", trans.contentNode).click(trans.moveRight);

    //experimental
    $("td.google-map-right a[href=" + location.pathname + "]").addClass("strong");

    $("div.teaser-content-bottom > div.teaser:eq(2)").addClass("last");


    $("ul li ul").children("li:eq(0)").addClass("first");

    $(".newsletter-close").click(function () {
        $(".newsletter-box").fadeOut();
        var exdate = new Date(),
            oneYear = exdate.getTime() + (360 * 24 * 60 * 60 * 1000);
        exdate.setTime(oneYear);
        document.cookie = "newsletter_closed=true;expires=" + exdate.toGMTString() + ";path=/";
    });

    $(".appointment-closed", ".appointment-listing").live("click", function () {
        $(this).removeClass("appointment-closed")
                .find(".appointment-further")
                .slideDown("fast", function () {
                    $(this).find("img").fadeIn("fast");
                });
    });

    $(".appointment-open-close", ".appointment-listing").live("click", function () {
        var that = $(this),
            parent = that.parent(),
            img = parent.find("img"),
            further = parent.find(".appointment-further");
        parent.addClass("appointment-closed");
        if (img.length) {
            img.fadeOut("fast", function () {
                further.slideUp("fast");
            });
        } else {
            further.slideUp("fast");
        }
    });

    $(".link-legend > div").click(function () {
        var that = $(this),
            links = $(".link-listing"),
            wantedClass = that.attr("class").replace(/link\-/, "");

        if (wantedClass === "all") {
            links.children().slideDown();
            return;
        }

        links.children(
            [":not(.", wantedClass, ")"].join("")
        ).slideUp();

        links.children(
            "." + wantedClass
        ).slideDown();
    });

    trans.placeZoom();
    trans.renderGlossary();
    trans.arrangeTeasers();
    trans.alignLeftRightContent();

    var newsletter = {

        elements: {},

        init: function () {

            newsletter.elements.jForm = $("#NewsletterForm");
            newsletter.elements.jActionField = $("#NewsletterForm_action");
            newsletter.elements.jLastNameField = $("#NewsletterForm_last_name");
            newsletter.elements.jFirstNameField = $("#NewsletterForm_first_name");
            newsletter.elements.jEmailField = $("#NewsletterForm_email");
            newsletter.elements.jCheckBox = $("#NewsletterForm_checkbox");
            newsletter.elements.jSubscribeButton = $("#NewsletterForm_button_subscribe");
            newsletter.elements.jUnsubscribeButton = $("#NewsletterForm_button_unsubscribe");

            newsletter.elements.jSubscribeButton.click(function () {
                newsletter.elements.jActionField.val("subscribe");
                if (newsletter.checkForm()) {
                    newsletter.elements.jForm.submit();
                }
            });

            newsletter.elements.jUnsubscribeButton.click(function () {
                newsletter.elements.jActionField.val("unsubscribe");
                if (newsletter.checkForm()) {
                    newsletter.elements.jForm.submit();
                }
            });

        },

        checkForm: function () {
            newsletter.elements.jEmailField.val($.trim(newsletter.elements.jEmailField.val()));
            // TODO: why do we have to bother the user like that?
            if (!(/^[^\s()<>@,;:\/]+@\w[\w\.\-]+\.[a-z]{2,}$/i)
                    .test(newsletter.elements.jEmailField.val())) {
                newsletter.elements.jEmailField.focus();
                alert("Bitte geben Sie eine valide Email-Adresse an.");
                return false;
            }

            newsletter.elements.jCheckBox.val(newsletter.elements.jCheckBox.val());
            if (newsletter.elements.jActionField.val() === "subscribe" &&
                    typeof $("#NewsletterForm :checked[name='checkbox']").val() === "undefined") {
                newsletter.elements.jCheckBox.focus();
                alert("Bitte akzeptieren Sie die Nutzungsbedingungen.");
                return false;
            }

            return true;
        }

    };

    $(newsletter.init);

} else {

    $(document).ready(function () {

        // /erfahrungsberichte/(.*/)?index.html --> Button [Add Content]
        $("div.containerControls > div[id^='showHide']").css("float", "left");
        $("body").attr("class", "editMode");

        $(".newsletter-close").click(function () {
            $(".newsletter-box").fadeOut();
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + 365);
            document.cookie = "newsletter_closed=true;expires=" + exdate.toUTCString() + ";path=/";
        });

    });
}
