/*jslint bitwise: true, browser: true, eqeqeq: true, immed: true, newcap: true, nomen: true, onevar: true, plusplus: true, regexp: true, undef: true, white: true, maxerr: 50, indent: 4 */
/*global console, $, dotLBInitialize, transplantationGlossary, window */

if (typeof dotLBInitialize === "undefined") {

    if (typeof String.trim === "undefined") {
        String.prototype.trim = function () {   // missing method trim for all strings
            return this.replace(/^\s+|\s+$/g, "");
        };
    }

    var trans = (function () {
        // private
        var body = $(document.body),
            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
                };
            },

            getWindowHeight = function () {
                return window.innerHeight || document.body.clientHeight ||
                        document.documentElement.clientHeight || null;
            },

            getWindowWidth = function () {
                return window.innerWidth || document.body.clientWidth ||
                        document.documentElement.clientWidth || null;
            };

        // public
        return {
            "log": typeof console !== "undefined" &&
                    typeof console.log === "function" ? console.log : function () {
                var div = document.createElement("DIV");
                div.className = "log";
                div.innerHTML = !arguments.length ? "" : (function (a) {
                    for (var i = 0, k = a.length, r = []; i < k; i += 1) {
                        r.push(a[i]);
                    }
                    return r.join(", ").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                }(arguments));
                document.body.appendChild(div);
            },

            "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 = getWindowWidth(),
                                windowheight = getWindowHeight();

                            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 () {
                $("div#content .text-content .meta-info .headline").
                    toggleClass("open").toggleClass("closed").
                            next().slideToggle();
            },

            "loadOverview": function () {
                var overviewUrl = $("div#content .text-content a.overview").
                        attr("href");
                if (!$("div#content .text-content div.overview").length) {
                    $("div#content .text-content").
                            append(['<div class="overview hidden"></div>'].join(""));
                    $("div#content .text-content 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 () {
                $("div#content .text-content div.overview, div#content .text-content div.step").
                        slideToggle();
                return false;
            },

            "moveLeft": function () {
                var ulContainerNode = $("div#content .gallery .slide-container ul"),
                    newMargin = parseInt(ulContainerNode.css("margin-left"), 10) +
                            (moveInterval * 3);

                newMargin = newMargin > 0 ? 0 : newMargin;
                ulContainerNode.stop().animate({
                    marginLeft: newMargin + "px"
                }, 1000, "swing");
            },

            "moveRight": function () {
                //Check the length of the slide-container
                var containerLength = $("div#content .gallery .slide-container ul li").
                        length * moveInterval,
                    ulContainerNode = $("div#content .gallery .slide-container ul"),
                    newMargin = parseInt(ulContainerNode.css("margin-left"), 10) -
                            (moveInterval * 3),
                    minMargin = -containerLength + 5 * moveInterval,
                    width = $("div#content .gallery .slide-container").width();

                if (containerLength > width) {
                    ulContainerNode.
                            css("width", containerLength + "px").stop().
                            animate({
                        marginLeft: newMargin < minMargin ? minMargin : newMargin + "px"
                    }, 1000, "swing");
                }
            },

            "alignLeftRightContent": function () {
                var left = $("div#content div.teaser-content-left, div.text-content-left"),
                    right = $("div#content div.teaser-content-right, div.text-content-right"),
                    leftheight = left.height(),
                    rightheight = right.height();
                if (leftheight > rightheight) {
                    right.css("height", leftheight + "px");
                }
            },

            "renderGlossary": function () {  // searchs side for glossary entries
                if (typeof transplantationGlossary !== "undefined" &&
                        transplantationGlossary) {
                    var key, node, text;

                    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) {
                                delete transplantationGlossary.end_____;  // unneeded delimiter
                                for (key in transplantationGlossary) {
                                    if (transplantationGlossary.hasOwnProperty(key)) {
                                        text = text.replace(
                                                new RegExp(["(>[^<]*)(", key, ")"].join("")),   //first param
                                                ["$1", '<span class="glossar" sltitle="',       //second param
                                                transplantationGlossary[key], '">',
                                                "$2", '</span>'].join(""));
                                    }
                                }
                                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>').
                        children("img.zoom");
                return zoom;
            }
        };
    }());

    $(document).ready(function () {
        $("span.glossar, a.question").mouseover(trans.tooltip);
        $("span.glossar").mouseout(trans.extooltip);
        $("a.question").mouseout(trans.setQuestionTimeout);

        $("div#content .text-content a.overview").
                livequery("click", trans.loadOverview);

        $("div#content .text-content a.close").
                livequery("click", trans.toggleOverview);

        $("div#content .text-content .meta-info .headline").
                livequery("click", trans.toogleMetaInfo);

        $("div#content .gallery .slider-left").click(trans.moveLeft);

        $("div#content .gallery .slider-right").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");

        trans.placeZoom();
        trans.alignLeftRightContent();
        trans.renderGlossary();

        //easteregg start
        /* var threetimeseasteregg = 0;
        $("div#content .gallery .slider-right").dblclick(function () {
            threetimeseasteregg += 1;
            if (threetimeseasteregg === 3) {
                //console.log($("slide-container > ul"));
                $(".slide-container > ul").append('<li class="item"><div class="title">Beaker</div><a href="/sonstiges/beaker/"><img alt="" src="/sonstiges/beaker/beaker.png"/></a><div class="bottom"><a class="button more" href="/sonstiges/beaker/"><span>Mi Mi Mi</span></a></div></li>');
            }
        }); */
        //easteregg end
    });

    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.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() {

            // window.alert("checking gender...");
            if(newsletter.elements.jActionField.val() === "subscribe" && typeof $("#NewsletterForm :checked[name='gender']").val() === "undefined") {
                $("#NewsletterForm :radio[name='gender']").get(0).focus();
                window.alert("Bitte wählen Sie eine Anrede.");
                return false;
            }

            // window.alert("checking last name...");
            newsletter.elements.jLastNameField.val(newsletter.elements.jLastNameField.val().trim());
            if(newsletter.elements.jActionField.val() === "subscribe" && newsletter.elements.jLastNameField.val() === "") {
                newsletter.elements.jLastNameField.focus();
                window.alert("Bitte geben Sie Ihren Nachnamen an.");
                return false;
            }

            // window.alert("checking first name...");
            newsletter.elements.jFirstNameField.val(newsletter.elements.jFirstNameField.val().trim());
            if(newsletter.elements.jActionField.val() === "subscribe" && newsletter.elements.jFirstNameField.val() === "") {
                newsletter.elements.jFirstNameField.focus();
                window.alert("Bitte geben Sie Ihren Vornamen an.");
                return false;
            }

            // window.alert("checking email address...");
            newsletter.elements.jEmailField.val(newsletter.elements.jEmailField.val().trim());
            if(!(/^[^\s()<>@,;:\/]+@\w[\w\.\-]+\.[a-z]{2,}$/i).test(newsletter.elements.jEmailField.val())) {
                newsletter.elements.jEmailField.focus();
                window.alert("Bitte geben Sie eine valide Email-Adresse an.");
                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");
    });
}
