// -------------------------------------------------------------------------------

var EE = {

    init: function() {
        this.adjustIFrameHeights();
        this.replaceMainNavElements();
        this.replaceSearchMenu();
        this.applySIFR();
        this.addInputScripts();
        this.removePageTitle();
        this.adjustLeftNav();
        this.adjustSiteSearchResults();
        this.adjustFooters();
        this.adjustElements();
        this.replaceLinks(".linkUeberschrift");
        this.replaceLinks("#applyDirectly .link");
        this.replaceLinks(".buttonPfeilLinks");
        this.replaceLinks(".contactMapPart .button");
        this.replaceLinks("#footer .left li a");
        this.replaceLinks("#newsletterContainer .preview");
        this.replaceLinks("#newsletterContainer .unsubscribe");
        this.replaceLinks(".buttonDoppelSchraegstrich");
        this.replaceLinks(".wpBranchLocator .link, .wpBranchLocator .linkClear");
        this.addImageRotatorScript();
        this.addFilterBoxScript();
        this.addContactFormScript();
        this.addPressFormScript();
        this.addSubmitHandlers();
        this.applyTipsy();

        // IE Hack: sometimes IE only applies styles when moving the mouse over them
        // appending a empty style tag seems to trigger re-applying of styles.
        $(document.body).append('<style type="text/css"></style>');
    },
    replaceMainNavElements: function() {

        var _this = this;
        var nav = $('#primaryNav');
        var new_nav = $('<div></div>');

        $("li", nav).each(function(i, e) {

            var link = $('a', e);
            var parts = link.text().split(':');

            if (parts[0].indexOf("Startseite") < 0 && parts[0].indexOf("Presse") < 0 && parts[0].indexOf("English") < 0 && parts[0].indexOf("Service") < 0) {

                var id = 'primaryNav' + i;
                var newLink = '<a href="' + link.attr('href') + '" title="' + parts[1] + '">';
                var item = $(
                    '<div id="' + id + '" class="item' + ($(e).hasClass('selected') ? ' selected' : '') + '">' +
					'<a href="' + link.attr('href') + '" title="' + parts[1] + '"><span class="clickfix"></span></a>' +
                    '<a class="heading" href="' + link.attr('href') + '" title="' + parts[1] + '">' + $.trim(parts[0]) + ':</a>' +
                    '<span class="name">' + newLink + $.trim(parts[1]) + '</a></span>' +
                    '</div>');

                _this.disableSelection(item);

                new_nav.append(item);

                $(item).mouseover(function() {

                    $("div.item", nav).each(function(i, e) {
                        $(e).removeClass('highlight');
                    });
                    $(item).addClass('highlight');
                });

                $(item).mouseout(function() {
                    $("div.item", nav).each(function(i, e) {
                        $(e).removeClass('highlight');
                    });
                });
            }
        });

        new_nav.append('<div class="clear"></div>');

        nav.empty();
        nav.append(new_nav);
    },
    replaceSearchMenu: function() {

        var _this = this;

        var label = $('<div class="label">Suche:</div>');
        label.click(function() { _this.toggleSearchBox(); });
        label.insertBefore($("#genericSearch input"));

        $("#genericSearch input").attr("title", "Bitte Suchbegriff eingeben ...");
        $('#genericSearch .ms-sbgo a').addClass('buttonBlauGrueneSchrift');
        $('#genericSearch .ms-sbgo img').replaceWith('suchen');

        var inner = $('<div class="inner"></div>');
        inner.append($(".searchBoxContainer input[type='hidden']"));
        inner.append($(".ms-sbtable", $(".N1 .searchBoxContainer")));

        $('#genericSearch').replaceWith(inner);
        $('.N1 .searchBoxContainer .ms-sbcell input').after('<div class="clear"></div>');
        $('.N1 .searchBoxContainer').after('<div class="clear"></div>');

        var input = $(".N1 .searchBoxContainer .ms-sbcell input");
        $("a", ".N1 .links").each(function(i, e) {

            if ($(e).text() == "Suche") {

                $(e).click(function() {

                    _this.toggleSearchBox();
                    return false;
                });
            }
        });
    },
    toggleSearchBox: function() {

        var search = $(".N1 .searchBoxContainer");

        var duration = 500;
        var easing = "swing";

        if (!search.is(":visible")) {

            search.animate({ width: "261px" }, duration, easing);
        } else {
            search.animate({ width: "1px" }, duration, easing,
                function() { search.hide(); });
        }
    },
    adjustLeftNav: function() {

        $(".A02 h3").remove();
        this.tagNavItems($(".A02 .content .links"), 0);
    },
    tagNavItems: function(parent, level) {

        var _this = this;
        var childSelected = false;

        $(parent).children("li").each(function(i, e) {

            $(e).children("a").each(function(i, e) {
                $(e).wrap('<div class="leftNav' + level + '"><div class="text"></div></div>');
            });

            $(e).children("ul").each(function(i, ul) {
                if (_this.tagNavItems(ul, level + 1))
                    $(e).addClass("childSelected");
            });

            if ($(e).hasClass("selected"))
                childSelected = true;
        });

        return childSelected;
    },
    adjustFooters: function() {

        $("#footer .left li").each(function(i, e) {

            var link = $("a", e);
            link.addClass("buttonPfeilLinksWeisserHintergrund");
            link.attr("title", link.text());
        });

        var copyright = $('<div class="copyright"></div>');
        $("#printFooter").append(copyright);

        $("#printFooter").contents().each(function(i, e) {

            if (e.nodeType == 3 || e.nodeName.toLowerCase() == "u") {

                var text = $.trim(e.nodeValue);
                if (text != "") {
                    $(copyright).append("<span>" + text + "</span>");
                    $(e).remove();
                } else
                    if (e.nodeType == 1) {
                    $(copyright).append(e);
                }
            }
        });
        $("#printFooter .copyright u").after('<div class="clear"></div>');
    },
    adjustElements: function() {

        $(".teaserBox .teaser").each(function(i, e) {
            $("a.buttonPfeilRechtsWeisserHintergrund, img", e).wrapAll('<div class="imgAndLink"></div>');
            $(".text", e).wrapInner('<div class="content"></div>');
            $(".text", e).after('<div class="clear"></div>');
        });

        $(".textContainer .bildTextZweispaltig .rechteSeite").each(function(i, e) {
            $(e).html('<div class="text">' + $(e).html() + '</div>');
        });

        if ($("#jobSearchFrameLarge").length > 0)
            $("#rightTop").addClass("largeContentHeader");

        $("iframe").each(function(i, e) {
            $(e).attr("scrolling", "no");
            $(e).attr("frameborder", "no");
            $(e).attr("allowtransparency", "true");
        });

        $("a > img").each(function(i, e) { $(e).parent().addClass("keineUnterstreichung"); });

        $("#contentTripletContainer").each(function(i, e) {

            if (!$("#contentTripletTop .innerContainer").html() &&
                !$("#contentTripletLeft .innerContainer").html() &&
                !$("#contentTripletMiddle .innerContainer").html() &&
                !$("#contentTripletRight .innerContainer").html())
                !$(e).addClass("hidden");
        });

        // fix paragraph in <li> generated by RTE
        $("li p").each(function(i, e) {
            $(e).replaceWith($(e).contents());
        });

        // fix CTA HTML
        $(".callToAction").each(function(i, e) {

            var top = $('<div class="topRow"></div>');
            $(top).append($("h3", e));

            var mid = $('<div class="middleRow"><div class="leftPane"></div><div class="rightPane"></div></div>');
            $(".leftPane", mid).append($(".leftPane img", e));
            $(".rightPane", mid).append($(".rightPane img", e));
            $(mid).append('<div class="clear"></div>');

            var bot = $('<div class="bottomRow"><div class="leftPane"></div><div class="rightPane"></div></div>');
            $(".leftPane", bot).append($(".leftPane .text", e));
            $(".rightPane", bot).append($(".rightPane .text", e));
            $(bot).append('<div class="clear"></div>');

            var btn = $('<div class="buttons"><div class="leftPane"></div><div class="rightPane"></div></div>');
            $(".leftPane", btn).append($(".leftPane a", e));
            $(".rightPane", btn).append($(".rightPane a", e));
            $(btn).append('<div class="clear"></div>');

            $(e).html("");
            $(e).append(top);
            $(e).append(mid);
            $(e).append(bot);
            $(e).append(btn);
        });

        // hide SP header if no content (removing large border)
        // .is(":empty") does not work in IE
        if ($.trim($("#MasterHeader").html()) != "")
            $("#MasterHeader").css("display", "block");
    },
    addInputScripts: function() {

        this.inputDefaultValue(".N1 #searchBoxContainer input", "Bitte Suchbegriff eingeben ...");
        this.inputDefaultValue("#newsletterContainer .email input", "Ihre E-Mail-Adresse");
        this.inputDefaultValue(".jobSearchHome input", "Job-Titel oder Stichwort");
        this.inputDefaultValue(".jobSearchSmall input", "Job-Titel oder Stichwort");
        this.inputDefaultValue(".jobSearchLarge input", "Job-Titel oder Stichwort");

    },
    inputDefaultValue: function(selector, text) {

        $(selector).each(function() {

            if (this.type != 'text' && this.type != 'password' && this.type != 'textarea')
                return;

            $(this).val(text);

            var fld_current = this;
            $(this).focus(function() {
                if (this.value == text || this.value == '') {
                    this.value = '';
                    $(this).addClass("userInput");
                }
            });

            $(this).blur(function() {
                if (this.value == text || this.value == '') {
                    this.value = text;
                    $(this).removeClass("userInput");
                }
            });

            $(this).parents("form").each(function() {
                $(this).submit(function() {
                    if (fld_current.value == text) {
                        fld_current.value = '';
                    }
                });
            });
        });
    },
    validateContactFormField: function(input, error) {

        //CAP:Warning, this query is case sensitive and the $ was added, because it was only

        //matching exact names witout it
        var input = $("input[name$=" + input + "]");
        if (input.val() == "") {

            input.addClass("highlight");
            $(error).removeClass("hidden");
            return false;

        }

        input.removeClass("highlight");
        $(error).addClass("hidden");

        return true;

    },
    validateContactForm: function() {

        var valid = true;

        //CAP:Replaced names with exact suffix
        if (!this.validateContactFormField("txtName", ".contactNameError")) valid = false;
        if (!this.validateContactFormField("txtPhoneOrEmail", ".contactMailError")) valid = false;

        return valid;

    },
    validatePressForm: function() {

        var valid = true;

        //CAP:Replaced names with exact suffix
        if (!this.validateContactFormField("txtPublisherCompany", ".publisherCompanyError")) valid = false;
        if (!this.validateContactFormField("txtDepartment", ".departmentError")) valid = false;
        if (!this.validateContactFormField("txtFirstName", ".firstNameError")) valid = false;
        if (!this.validateContactFormField("txtLastName", ".lastNameError")) valid = false;
        if (!this.validateContactFormField("txtPhone", ".phoneError")) valid = false;
        if (!this.validateContactFormField("txtEmail", ".emailError")) valid = false;

        return valid;

    },
    addContactFormScript: function() {

        /*

        CAP:Due to ASP.NET web control design, it is not possible for a LinkButton control to
        have a conditional postback, in the following code we inject the form validation into
        the event handler to make it possible.

        */

        if ($("#contactForm").length > 0) {
            var onClickCode = "if(EE.validateContactForm())" + $("#contactForm .submit").attr("href").replace("javascript:", "")
            $("#contactForm .submit").attr("href", "javascript:" + onClickCode)
            $("#contactForm input").keypress(function(event) {

                if (event.which == 13) {

                    eval(onClickCode);

                }
            });
        }
    },
    addPressFormScript: function() {

        /*
        // added 21.06.2010
        CAP:Due to ASP.NET web control design, it is not possible for a LinkButton control to
        have a conditional postback, in the following code we inject the form validation into
        the event handler to make it possible.

        */

        if ($("#DivPressDistributionList").length > 0) {
            var onClickCode = "if(EE.validatePressForm())" + $("#DivPressDistributionList .submit").attr("href").replace("javascript:", "")
            $("#DivPressDistributionList .submit").attr("href", "javascript:" + onClickCode)
            $("#DivPressDistributionList input").keypress(function(event) {

                if (event.which == 13) {

                    eval(onClickCode);

                }

            });
        }
    },
    addSubmitHandlers: function() {
        $("#newsletterContainer .email .subscribe").click(function() {
            $(this).parents("form").submit();
        });
        $(".jobSearchResults .searchOptions .submit").click(function() {
            $(this).parents("form").submit();
        });
        $(".jobSearchResults .filterCity .buttonPfeilLinks").click(function() {
            $(this).parents("form").submit();
        });
        $(".jobSearchHome .buttonBlauGrueneSchrift").click(function() {
            $(this).parents("form").submit();
        });
        $(".jobSearchSmall .buttonBlauGrueneSchrift").click(function() {
            $(this).parents("form").submit();
        });
        $(".jobSearchLarge .button").click(function() {
            $(this).parents("form").submit();
        });
    },
    disableSelection: function(selector) {
        if ($.browser.mozilla) {
            $(selector).css('MozUserSelect', 'none');
        } else if ($.browser.msie) {
            $(selector).bind('selectstart', function() { return false; });
        } else {//Opera, etc.
            $(selector).mousedown(function() { return false; });
        }
    },
    imageRotatorTimer: function() {

        if (++this.currentRotatedImage >= this.rotatedImages.length) {
            this.currentRotatedImage = 0;
        }

        for (var i = 0; i < this.rotatedImages.length; i++) {

            if (i == this.currentRotatedImage) {
                $(this.rotatedImages[i]).css("display", "block");
            } else {
                $(this.rotatedImages[i]).css("display", "none");
            }
        }
    },
    addImageRotatorScript: function() {

        var images = $(".imageRotator img");
        if (images.length <= 0)
            return;

        this.currentRotatedImage = 0;
        this.rotatedImages = Array();
        var _this = this;

        images.each(function(i, e) {
            if (i == 0)
                $(e).css("display", "block");
            _this.rotatedImages[i] = e;
        });

        window.setInterval(function() {
            _this.imageRotatorTimer();
        }, 4000);
    },
    adjustSiteSearchResults: function() {

        // top menu

        $("#SRCHRSSI").replaceWith("");

        var items = $(".searchSite .srch-sort-right").contents().filter(function() { return this.nodeType == 3 || this.nodeType == 1; });
        var newItems = $('<div class="searchOptions"></div>');

        items.each(function(i, e) {

            if (e.nodeType == 3) {

                var text = $.trim(e.nodeValue);
                if (text.length > 0)
                    $(newItems).append($('<span class="item">' + text + '</span>'));

            } else {
                var item = $('<span class="item"></span>');
                $(item).append(e);
                $(newItems).append(item);
            }
        });
        $(".searchSite .srch-sort-right").replaceWith(newItems);
        $(newItems).parent().append($('<span class="clear"></span>'));

        // pagination

        $(".searchSite .srch-Page").each(function(i, e) {

            var newBar = $('<div class="pageBar"></div>');

            var childrenWithText = $(e).contents().filter(function() { return this.nodeType == 3 || this.nodeType == 1; });
            $(childrenWithText).each(function(j, c) {

                if (c.nodeType == 1) {

                    var text = $(c).text().replace(/>|</, "");
                    var item = $('<a href="' + $(c).attr('href') + '" title="' + $(c).attr('title') + '">' +
                                '<span class="pageNo' + (c.id == "SRP_Prev" ? " prevPage" : "") + (c.id == "SRP_Next" ? " nextPage" : "") + '">' +
                                '<span class="text">' + text + '</span>' +
                                '</span>' +
                                '</a>');
                    $(newBar).append(item);

                } else
                    if (c.nodeType == 3) {

                    var text = $.trim(c.nodeValue);
                    if (text.match(/[\s0-9a-z<>]+/))
                        $(newBar).append($('<span class="pageNo pageNoActive">' + text + '</span>'));

                }
            });

            $(newBar).append($('<span class="clear"></span>'));
            $(newBar.parent()).append($('<span class="clear"></span>'));

            $(e).replaceWith(newBar);
        });

        var results = $(".searchSite .srch-results").children();
        var newResults = $('<div class="srch-results"></div>');

        for (var i = 0; i < results.length; i += 4) {

            var row = $('<div class="row ' + (i / 4 % 2 == 0 ? "even" : "odd") + '"></div>');
            $(newResults).append($(row));

            var meta = $('<div class="srch-Metadata"></div>');
            $(results[i + 3]).contents().each(function(i, e) {

                if (e.nodeType == 3) {

                    var reSize = /([\d]*KB)/gi;
                    var reDate = /([\d]*\/[\d]*\/[\d]*)/gi;

                    var size = e.data.match(reSize);
                    var date = e.data.match(reDate);

                    if (size) meta.append("&nbsp;-&nbsp;" + size[0]);
                    if (date) meta.append("&nbsp;-&nbsp;" + date[0]);

                } else
                    $(meta).append(e);
            });

            row.append(results[i]);
            // skip title
            row.append(results[i + 2]);
            row.append(meta);
        }
        $(".searchSite .srch-results").replaceWith(newResults);
    },
    replaceLinks: function(selector) {

        $(selector).each(function(i, e) {

            var elementType = "div";
            var wrapper = $('<' + elementType + ' class="linkWrapper"></' + elementType + '>');
            $(wrapper).append('<' + elementType + ' class="linkArrow"></' + elementType + '>');
            $(wrapper).append('<' + elementType + ' class="linkText"></' + elementType + '>');
            $(wrapper).append('<' + elementType + ' class="clear"></' + elementType + '>');
            $(".linkText", wrapper).append($(e).clone());
            $(wrapper).attr("class", $(e).attr("class"));
            $(wrapper).attr("style", $(e).attr("style"));
            $(wrapper).css("background-image", "none");
            $(e).replaceWith(wrapper);
        });
    },
    removePageTitle: function() {
        var title = $("#pageTitle");
        if ($.trim(title.text()) == "")
            title.remove();
    },
    applyTipsy: function() {

        var e = $(".jobSearchResults .searchOptions .filter .remove");
        if (e.length > 0) $(e).tipsy({ gravity: 's' });

        e = $(".jobSearchResults .searchOptions .filter a.eeGruen");
        if (e.length > 0) $(e).tipsy({ gravity: 's' });
    },
    adjustIFrameHeights: function() {

        $("iframe").each(function(i, e) {
            $(e).attr("allowtransparency", "true");
        });

        // on embedding page?
        if (typeof $ == "function" && typeof $.receiveMessage == "function") {
            var iframe = document.getElementById('jobSearchIFrame');
            if (iframe) {
                $.receiveMessage(function(e) { $(iframe).css('height', e.data + 'px'); });
                // force iframe to reload, so that our message handler is triggered (the line above registers it after the frame was loaded).
                iframe.src = iframe.src + (iframe.src.indexOf('?') == -1 ? '?' : '&') + "tick=" + new Date().getTime() + "#" + encodeURIComponent(document.location.href);
            }
        }

        // in iframe?
        var _this = this;
        var frame_body = $("body.jobSearchResultsFrame");
        if (frame_body && frame_body.length > 0) {

            window.setInterval(function() {

                var height = $(".jobSearchResults").height() + 120;
                if (typeof _this.iframeHeight == "undefined" || height != _this.iframeHeight) {
                    var parent_url = decodeURIComponent(document.location.hash.replace(/^#/, ''));
                    $.postMessage("" + height, parent_url, parent);
                }

                _this.iframeHeight = height;

            },
            // lower update rate for IE (slow)
			$("body").hasClass("ie") ? 1000 : 100);
        }
    },
    addFilterBoxScript: function() {

        $('.jobSearchResults .filterBox').each(function(i, box) {

            var items = [];
            $('.filters div', box).each(function(i, e) { items.push(e); });

            $("a[rel='SortCount']", box).click(function(e) {

                items.sort(function(a, b) {

                    var s1 = $('.count', a).text();
                    var c1 = parseInt(s1.substr(2, s1.length - 3));
                    var s2 = $('.count', b).text();
                    var c2 = parseInt(s2.substr(2, s2.length - 3));

                    return c1 < c2 ? -1 : (c1 > c2 ? 1 : 0);
                });

                $('.filters div', box).remove('*');
                $(items).each(function(i, e) { $('.filters', box).append(e); });

                e.preventDefault();
                return 0;
            });

            $("a[rel='SortAlpha']", box).click(function(e) {

                items.sort(function(a, b) {

                    var s1 = $('.filter', a).text();
                    var s2 = $('.filter', b).text();
                    return s1.localeCompare(s2);
                });

                $('.filters div', box).remove('*');
                $(items).each(function(i, e) { $('.filters', box).append(e); });

                e.preventDefault();
                return 0;
            });

        });
    },
    initSIFR: function() {

        if ((typeof window.sIFR != "object") || (typeof window.sIFR.activate != "function"))
            return;

        sIFR.useStyleCheck = false;
        sIFR.autoInitialize = false;

        this.conduit = { src: '/_controltemplates/Cap_DE_EE/flash/ee-conduit-light.swf ' };
        sIFR.activate(this.conduit);
    },
    applySIFR: function() {

        if ((typeof window.sIFR != "object") || (typeof window.sIFR.activate != "function"))
            return;

        var items = $("#primaryNav .item");
        if (!items)
            return;

        var menu_item_count = items.length;
        var items_replaced = 0;

        sIFR.replace(this.conduit,
        {
            selector: "#primaryNav .name",
            wmode: "transparent",
            forceSingeLine: true,
            pixelFont: true,
            selectable: false,
            antiAliasType: "normal",
            css: [
                '.sIFR-root { font-size:19px; }',
                'a { color:#00356f; text-decoration:none; }',
                'a:link { color: #00356f; }',
                'a:hover { color: #00356f; }'
            ],
            onReplacement: function() {
                // HACK: hide nav as long as replacement is not done yet
                if (++items_replaced >= menu_item_count) {
                    $('#primaryNav').css('visibility', 'visible');
                }
            }
        });

        sIFR.replace(this.conduit,
        {
            selector: "#companyClaim h3",
            wmode: "transparent",
            forceSingeLine: false,
            pixelFont: true,
            selectable: false,
            antiAliasType: "normal",
            css: ['.sIFR-root { font-size:32px; color:#005187; leading:-5px; }']
        });
        sIFR.replace(this.conduit,
        {
            selector: "#companyClaim h4",
            wmode: "transparent",
            forceSingeLine: false,
            pixelFont: true,
            selectable: false,
            antiAliasType: "normal",
            css: ['.sIFR-root { font-size:19px; color:#005187; leading:-5px; }']
        });

        sIFR.replace(this.conduit,
        {
            selector: "#applyDirectly h3",
            wmode: "transparent",
            forceSingeLine: true,
            pixelFont: true,
            selectable: true,
            antiAliasType: "normal",
            css: ['.sIFR-root { font-size:20px; color:#00356f; }']
        });

        sIFR.replace(this.conduit,
        {
            selector: ".quote h3",
            wmode: "transparent",
            forceSingeLine: true,
            pixelFont: true,
            selectable: true,
            antiAliasType: "normal",
            css: ['.sIFR-root { font-size:18px; color:#5f5f5f; leading:-3px; }']
        });

        sIFR.initialize();
    }
}

// important: init sifr before onload
EE.initSIFR();

$(document).ready(function() { EE.init(); });

// -------------------------------------------------------------------------------