var highlight_color = '#950006';
var active_3rdlevel_menuitem = null;

(function() {

var tab_change_handler = function (event) {
    var tab_content_id = $(this).attr('href').split('?tab=')[1];
    var box_class = 'tab_' + tab_content_id.split('_')[1];
    $('.' + box_class).addClass('invisible');
    $('#' + tab_content_id).removeClass('invisible');
    $(this).parents('ul.tabnav').find('li').removeClass('active');
    $(this).parents('li').addClass('active');
    event.preventDefault();
};

var empty_press_search_field = function () {
    if ($(this).val() == $(this).prev().text()) {
        $(this).val('');
    }
}

var init_languagemenu = function (obj) {
        var elem = $('#change_language .newListSelected .selectedTxt')[0];
        var pos = (obj.selectedIndex * -26) + 4;
        elem.style.backgroundPosition = '0pt ' + pos + 'px';
}

var sort_order_redirect = function(new_order) {
    var new_url = window.location.href;
    if (new_url.search(/\?/) == -1) {
        new_url = new_url + '?';
    }
    new_url = new_url.replace(/&sort-order=(rel|chrono)/, '');
    new_url = new_url + '&sort-order=' + new_order;
    window.location = new_url;
}


var horizontal_layout_adjust_boxes_without_categories = function() {
    //add an empty category div into boxes inside horizontal layout
    //if we only have boxes without categories, do nothing:
    $('div.horizontal').each(function(index, elem) {
        var horibox = $(elem);
        if (horibox.find('.category').length > 0) {
            horibox.find('div.box > div.teaser_content').each(function(index, elem) {
                var content_box = $(elem);
                if (content_box.next('.category').length == 0) {
                    content_box.after('<div class="category"><hr class="seperator" style="visibility:hidden;"></hr><span>&nbsp;</span></div>');
                }
            });
        }
    });
}

var horizontal_layout_adjust_boxes_without_topic = function() {
    //add an empty topic div into boxes inside horizontal layout
    //if we only have boxes without topic, do nothing:
    $('div.horizontal').each(function(index, elem) {
        var horibox = $(elem);
        if (horibox.find('.topic').length > 0) {
            horibox.find('div.box').each(function(index, elem) {
                var content_box = $(elem);
                if (content_box.children('.topic').length == 0) {
                    $('<div class="topic notheme">&nbsp;</div>').insertAfter(content_box.children('.teaser_content'));
                }
            });
        }
    });
}


var horizontal_layout_adjustment_start = function() {
    $('div.horizontal').each(horizontal_layout_adjustment);
}

var horizontal_layout_adjustment = function(index, elem) {
    var hori = $(elem);
    //check if we have images somewhere
    var images = hori.find('img');
    if (images.length != 0) {
        for (var image_index=0;image_index < images.length;image_index++) {
            image = $(images[image_index]);
            if (!image.height()) {
                window.setTimeout(horizontal_layout_adjustment_start, 300);
                return;
            }
        }
    }
    var max_height = 0;
    hori.find('div.box > div.teaser_content').each(function(index, subelem) {
        var content_box = $(subelem);
        if (content_box.height() > max_height) {
            max_height = content_box.height();
        }
    });
    hori.find('div.box > div.teaser_content').each(function(index, subelem) {
        var content_box = $(subelem);
        content_box.css('height', max_height);
    });
}


$().ready(function(ev) {
    //$('div.horizontal div.teaserimage img').one('load', horizontal_layout_adjustment_delayed).each(function() {if(this.height) $(this).trigger('load');});
    $('#searchresult_headlinesonly').removeClass('invisible');
    //$('ul.tabnav a').click(tab_change_handler); //removed in #2125
    $('#change_language_url').bind("change", function() {
        init_languagemenu(this);
        $('#submit_change_language').click();
    });
    var change_language_url = document.getElementById('change_language_url');
    if (change_language_url) {
      init_languagemenu(change_language_url);
    }

    $('#search_catselect').bind('change', function() {$('#category_submit').click();});
    $('#submit_change_language').focus();
    $('.press_searchfield').bind("focus", empty_press_search_field);
    $('#show_headlines_only').click(function() {
        if ($('#show_headlines_only')[0].checked && ($('div.pressrelease_wide_info')[0].style.display != 'none')) {
            return;
        }
        $('#searchresult_hitlist div.pressrelease_wide_info').slideToggle();
        $('#searchresult_hitlist hr.first').slideToggle();
        $('#searchresult_hitlist h5.article_subtitle').slideToggle();
        $('#searchresult_hitlist span.wide_desc').slideToggle();
        $('#searchresult_hitlist a.read_more').slideToggle();
        $('#searchresult_hitlist div.article_teaser div.teaserimage').slideToggle();
    });
    $('#press_search_button').bind('click', function() { $('#submit_press_search').click(); return false;});
    $('#submit_press_search').click(function(ev){
            if ($('.press_searchfield').val() == $('.press_searchfield').prev().text()) {
                $('.press_searchfield').val('');
            }
        });
    $('#dgb div#logo').click(function() { window.location = $(this).children('a')[0].href; });

    // Blendet das aktuelle Overlay-Menü aus, sobald man den Menü-Bereich verlässt.
    $('#dgb div.categories-pop-up').bind('mouseleave', function(ev) {
        if(this.id) $('#dgb #' + this.id).hide();
    });

    // Blendet das aktuelle Overlay-Menü aus, sobald man einen anderen Menüpunkt in der zweiten Ebene berührt.
    $('#dgb #main_nav ul.primary ul.secondary li').bind('mouseenter', function(ev) {
        if(active_3rdlevel_menuitem != null && this.id != active_3rdlevel_menuitem){
            $('#dgb #SUB' + active_3rdlevel_menuitem).hide();
            active_3rdlevel_menuitem = null;
        }
        $('#dgb div.categories-pop-up-all-pages').hide();
    });

    // Blendet das aktuelle Overlay-Menü aus, sobald man einen Menüpunkt in der ersten Ebene berührt.
    $('#dgb #main_nav ul.primary li.main_nav').bind('mouseenter', function(ev) {
        if(active_3rdlevel_menuitem != null){
            $('#dgb #SUB' + active_3rdlevel_menuitem).hide();
            active_3rdlevel_menuitem = null;
        }
        if (!$(this).hasClass('themes')) {
            $('#dgb div.categories-pop-up-all-pages').hide();
        }
    });
    $('input:radio').checkbox();
    $('#sort-order-switch input:submit').hide();
    $('#sort-order-switch-chrono').click(function() {
        sort_order_redirect('chrono');
    });
    $('#sort-order-switch-relevance').click(function() {
        sort_order_redirect('rel');
    });

    $('#dgb #main_nav ul li.themes').bind('mouseover', function(ev) {
        var popup = $('#dgb div.categories-pop-up-all-pages');
        var offsetLeft = $('#dgb #header li.themes')[0].offsetLeft;
        var offsetTop = $('#dgb #header #main_nav')[0].offsetTop + 32;
        popup.css({'left': offsetLeft + 'px', 'top': offsetTop + 'px'});
        popup.slideDown('fast', function() {
                if(active_3rdlevel_menuitem != null) $('#dgb #SUB' + active_3rdlevel_menuitem).hide();
    	});
        var border = RUZEE.ShadedBorder.create({corner:3, shadow:8});
        border.render($('#dgb div.categories-pop-up-all-pages ul'));
    });

    // Blendet ein Overlay-Menü der dritten Ebene ein.
    $('#dgb #main_nav ul.secondary li.withsub').bind('mouseover', function(ev) {
        var id = this.id;
        if(active_3rdlevel_menuitem != id){
            var popup = $('#dgb #SUB' + id);
            var offsetLeft = $('#dgb #header #' + id)[0].offsetLeft;
            var offsetTop = $('#dgb #header #main_nav')[0].offsetTop + 69;
            popup.css({'left': offsetLeft + 'px', 'top': offsetTop + 'px'});
	        popup.slideDown('fast', function() {
	        	if(active_3rdlevel_menuitem != id){
		        	if(active_3rdlevel_menuitem != null) $('#dgb #SUB' + active_3rdlevel_menuitem).hide();
		        	active_3rdlevel_menuitem = id;
	        	}
        	});
            var border = RUZEE.ShadedBorder.create({corner:3, shadow:8});
            border.render($('#dgb #SUB' + id + ' ul'));
    	}
    });    
    horizontal_layout_adjust_boxes_without_categories();
    horizontal_layout_adjust_boxes_without_topic();
    horizontal_layout_adjustment_start();
});

})();


(function() {
    // Highlight the glossar words

    var glossar_link_class_name = 'highlightedGlossarTerm';
    var word_char = /\w/;

    var climb = function(node, word, url){
        // traverse childnodes
        if (node.nodeType == node.TEXT_NODE) {
            checkforhighlight(node, word, url, 0);
            return
        }
        if (!node || !node.hasChildNodes || node.nodeName == 'TABLE') {
            return false
        }
        var i;
        for (i=0;i<node.childNodes.length;i++) {
            climb(node.childNodes[i], word, url);
        }
    }

    var checkforhighlight = function(node, word, url, start_index) {
        if (node.parentNode.nodeName != 'P' &&
            node.parentNode.nodeName != 'DIV') {
            return
        }
        if (node.parentNode.className == glossar_link_class_name) {
            return
        }
        ind = node.nodeValue.toLowerCase().indexOf(
            word.toLowerCase(), start_index);
        if (ind == -1) {
            return
        }
        if (ind > 0 && word_char.test(node.nodeValue[ind-1])) {
            // Substring match -> ignore
            checkforhighlight(node, word, url, ind+1);
            return
        }
        var char_after = node.nodeValue[ind + word.length];
        if (typeof(char_after) != "undefined" &&
            word_char.test(char_after)) {
            // Substring match -> ignore
            checkforhighlight(node, word, url, ind+1);
            return
        }
        par = node.parentNode;
        contents = node.nodeValue;

        // make 3 shiny new nodes
        hiword = document.createElement("a");
        hiword.className = glossar_link_class_name;
        hiword.href = url;
        hiword.appendChild(
            document.createTextNode(
                contents.substr(ind, word.length)));
        par.insertBefore(
            document.createTextNode(contents.substr(0, ind)), node);
        par.insertBefore(hiword,node);
        var text_after = par.insertBefore(
            document.createTextNode(
                contents.substr(ind+word.length)), node);
        checkforhighlight(text_after, word, url, 0);
        par.removeChild(node);
    }

    var set_position = function(div, x, y, y_offset) {
        var x = x - 20;
        var y_offset = div.height() + 5 + y_offset;
        var y = y - y_offset;
        div.css({
            'left': x + 'px',
            'top': y + 'px'
        });
        div.addClass('visible');
        return y_offset;
    }

    var show_glossar_popup = function(event) {
        event.preventDefault();
        var popup = $('#glossar-popup');
        var popup_line = $('#glossar-popup-line')
        $.get($(this).attr('href'), function(data) {
            var y_offset = set_position(
                popup_line, event.pageX, event.pageY, 0);
            popup.html(data);
            set_position(popup, event.pageX, event.pageY, y_offset);
        });
    }

    var hide_glossar_popup = function(event) {
        event.preventDefault();
        var popup = $('#glossar-popup');
        var popup_line = $('#glossar-popup-line')
        popup.removeClass('visible');
        popup_line.removeClass('visible');
        popup_line.html('');
    }

    var get_terms_and_highlight = function() {
        $.getJSON(
            uc_site_url + '/@@glossary-terms.json', null, function(data) {
            $().ready(function() {
                var node = document.getElementById('main_slot');
                $.map(data['terms'], function(term) {
                    climb(node, term.term, term.url);
                });
                $('a.' + glossar_link_class_name).click(show_glossar_popup);

                $('#glossar-popup h4 .close').live(
                    'click', hide_glossar_popup);
            });
        });
    };

    get_terms_and_highlight();


})();

