/* ******************************************************************** */
/* default webcenter js													*/
/* ******************************************************************** */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/*
jQuery Url Plugin
	* Version 1.0
	* 2009-03-22 19:30:05
	* URL: http://ajaxcssblog.com/jquery/url-read-get-variables/
	* Description: jQuery Url Plugin gives the ability to read GET parameters from the actual URL
	* Author: Matthias JÃ¤ggli
	* Copyright: Copyright (c) 2009 Matthias JÃ¤ggli 
	* Licence: dual, MIT/GPLv2
*/
(function ($) {
	$.url = {};
	$.extend($.url, {
		_params: {},
		init: function(){
			var paramsRaw = "";
			try{
				paramsRaw = 
					(document.location.href.split("?", 2)[1] || "").split("#")[0].split("&") || [];
				for(var i = 0; i< paramsRaw.length; i++){
					var single = paramsRaw[i].split("=");
					if(single[0])
						this._params[single[0]] = decodeURIComponent(single[1].replace(/\+/g, " "));
				}
			}
			catch(e){
				alert(e);
			}
		},
		param: function(name){
			return this._params[name] || "";
		},
		paramAll: function(){
			return this._params;
		}
	});
	$.url.init();
})(jQuery);
// Das Input-Feld für die Suche


// Banksearch functions
// ====================
function closeWindow( ) {
	if (window.lightbox) {
		window.lightbox.hide();
	}
}

function setFontSize(size) {
	getFlexApp("AddressFinder").setFontSize(size);
}

function getFlexApp(appName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[appName];
	} else {
		return document[appName];
	}
}

$(document).ready(function() {
	
	var field = $('.searchfield');
	if (!field) {
		return;
	}
	var q = $.url.param('q');
	if (q == '') {
		q = 'Suche';
	}
	
	field.val(q);
	
	field.blur(function() {
		if ($(this).val() == '') {
			$(this).val(q);
		}
	});
	
	field.click(function(){
		if ($(this).val() == q) {
			$(this).val('');
		}
	});
	
});


/* ******************************************************************** */
/* ******************************************************************** */

// add link to next event on top of eventdetails
function getNextEventLink() {
	url = window.location.href;
	var docRoot;
	docRoot = typeof CQ !== 'undefined' ? '/content/f0906-0/internet/website/' : '/';
	if(url.search('home\/termine\/') > -1){
		$.ajax({
			url : docRoot + 'home/termine.html',
			context : document.body,
			success : function(data) {
				links = $(data).find('#seiteninhalt .cmpTabelle a');
				var nextLink, nextFile;
				var url = window.location.href.split('/');
				var file = url[url.length-1];
				for (i = 0; i <= links.length-1; i++) {
					nextUrl = links[i].href.split('/');
					nextFile = nextUrl[nextUrl.length-1];
					if((file.search(nextFile) > -1) && (i != 0)){
						$('.link_back').after('<a title="_next_page" href="'+links[i-1].href+'" style="margin-left: 20px;"><span>zum nächsten Termin</span></a>');
					}
				}
			}
		});
	}
}

/* ******************************************************************** */
/* ******************************************************************** */


// Load all Top-Themen Pages for Print
// ===================================
var BuildTopThemaForPrint = function(){
	this.content = $('#content');
	if (this.content.length) {
		this.footer = this.content.find('#content_footer');
		this.footer_links = this.content.find('#footer_links');
		this.parse(this.content, null);
	}
};

BuildTopThemaForPrint.prototype = {

	prev_loaded: false,
	next_loaded: false,

	parse: function(wrapper, pos) {
		var next = wrapper.find('a[title=_next_page]'),
			prev = wrapper.find('a[title=_previous_page]'),
			next_to_top = (next.length && (next.attr('href').indexOf('top_themen.popup.html') !== -1 || next.attr('href').indexOf('top_themen.html') !== -1));

		// Next Pages
		if ((pos === null || pos === 'next') && next.length && next_to_top === false) {
			this.load(next.attr('href'), 'next');
		} else if ((pos === null || pos === 'next') && (next.length === 0 || next_to_top === true )) {
			this.next_loaded = true;
		}

		// Previous Pages
		if ((pos === null || pos === 'prev') && prev.length) {
			this.load(prev.attr('href'), 'prev');
		} else if ((pos === null || pos === 'prev') && prev.length === 0) {
			this.prev_loaded = true;
		}

		// remove lists
		if (next.length) {
			next.parents('.cmpLinkbox').first().remove();
		} else if (prev.length) {
			prev.parents('.cmpLinkbox').first().remove();
		}

		// finished loading
		if (this.next_loaded && this.prev_loaded) {
			this.print();
		}
	},

	load: function(url, pos) {
		var that = this;
		$.ajax(url, {
			dataType: 'html',
			type: 'GET',
			success: function(response) {
				that.loadSuccess(response, pos);
			},
			error: function() {
				that.print();
			}
		});
	},

	loadSuccess: function(response, pos) {
		var content = $(response).find('#content');
		if (content.length) {
			if (pos === 'next') {
				this.content.append(content.html());
				this.content.append(this.footer_links);
				this.content.append(this.footer);
			} else if (pos === 'prev') {
				this.content.prepend(content.html());
			}
			this.parse(content, pos);
		} else {
			this.print();
		}
	},

	print: function() {
		this.content.find('.cmpUeberschriftStandard .headline').each(function(index) {
			if (index !== 0) {
				$(this).remove();
			}
		});
		window.print();
	}
};

// Sort dynamic teaserlist by date
// ===============================

function sortNumbersDesc(a,b)
{
	return b - a;
}
	
function sortTeasersByDate() {
	
	// define vars
	var date,
		timestamp,
		news = {},
		keys = [],
		page = 0,
		count = 1,
		container = '.teaserListe',
		pageAmount = jQuery(container).length,
		elemAmount = jQuery(container+':first-child').find('.cmpBildTextTeaser').length;
		elemID = jQuery(container).attr('id').split('_render_',1);
	
	// get dates from each newsblock, convert to timestamp and write in news in object
	jQuery(container).find('.cmpBildTextTeaser').each(function() {
		date = jQuery(this).find('.text').text().trim().substring(0,10);
		timestamp = (new Date(Date.UTC(date.split('.')[2], date.split('.')[1]-1, date.split('.')[0]))).getTime()/1000;
		news[timestamp] = jQuery(this);
	});
	
	// write timestamps in keys array
	for(var k in news) {
		if(news.hasOwnProperty(k)) {
			keys.push(k);
		}
	}
	
	// empty container
	jQuery(container).empty();
	
	// sort keys desc
	keys.sort(sortNumbersDesc);
	
	// append sorted news to container
	for(i=0;i<keys.length;i++){
		jQuery('#'+elemID+'_render_'+page).append(news[keys[i]]);
		if(count == elemAmount){
			count = 0;						
			page++;
		}
		count++;
	}
}


// Document Ready
// ==============

$(document).ready(function(){

	var is_iframe = (window.top === window.self) ? false : true,
		no_back_link = ($.url.param('nobacklink')) ? true : false,
		content = $('#content'),
		is_edit_mode = false,
		is_cq = false,
		is_print_mode = ($.url.param('action') === 'print') ? true : false,
		document_body = $(document.body);

	if (typeof CQ !== 'undefined') {
		is_edit_mode = (CQ.WCM && CQ.WCM.getMode() === 'edit') ? true : false;
		is_cq = (CQ.WCM) ? true : false;
	}
	
	if (is_iframe && is_cq === false) {
		document_body.addClass('is_iframe');
	}

	site_operator.is_top_thema();
	
	getNextEventLink();

	// add click to banklogo
	var banklogo = $('#banklogo');
	if (banklogo.length) {
		banklogo.click(function(){
			window.location.href = 'http://' + window.location.hostname;
		}).css('cursor', 'pointer');
	}


	// set the h2 before h1 in dom
	// ===========================
	content.find('.cmpUeberschriftStandard h2').prependTo('#content .cmpUeberschriftStandard .headline');
	content.find('.cmpUeberschriftTeaser h2').prependTo('#content .cmpUeberschriftTeaser .headline');
	
	// insert link-container in content-footer
	// =======================================
	$('<div id="footer_links"><div class="clearing"></div></div>').appendTo('#content');
	
	// set popup-action on special buchtipps
	// =====================================
	$('a[title*="_leseprobe"], a[title*="_autor"]').each(function(){
		$(this).get(0).onclick = '';
		$(this).click(function(){
			window.open(this.href,'imPopup','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=625,height=625,left=100,top=50');
			return false;
		});
	});


	if (document_body.attr('id') === 'resource-alle_nachrichten' || document_body.attr('id') === 'resource-home') {
		var all_news_list = $('.cmpDynTeaserListe');
		if (all_news_list.length) {
			all_news_list.each(function(){
				site_operator.switchDynTeaserListe($(this), false);
			});
		}
	}

	// create paging for teaserlists
	// =============================
	var paging = {

		active: 0,
		active_page_element: null,
		max_page_links: 5,
		pages: [],
		pages_count: 0,
		page_links: [],
		morebox: null,
		pagingbox: null,
		browsebox: null,
		paging_html: $('<div class="dyn_teaser_paging">' +
							'<div class="morebox">' +
								'<a href="#" class="next">Weiter</a>'+
								'<a href="#" class="prev">Zurück</a>'+
							'</div>' +
							'<div class="divider"><!-- --></div>' +
							'<div class="browsebox">' +
								'<div class="overview">Seite <span class="active_page">1</span> von <span class="pages_count"></span> </div>' +
								'<div class="page_links">'+
								'</div>' +
							'</div>' +
							'<div class="pagingbox">' +
								'<a href="#" class="next">Weiter</a>'+
								'<a href="#" class="prev">Zurück</a>'+
							'</div>' +
						'</div>'),

		init: function() {
			var self = this;
			
			if (site_operator.is_detail_page() === true || site_operator.is_rubric_start_page() === true) {
				return;
			}
			
			// find elements
			this.wrapper = $('.cmpDynTeaserListe');
			if (this.wrapper.length) {
				this.pages = this.wrapper.find('div[id*="_render_"]');
				this.pages_count = this.pages.length;
				this.wrapper.find('.TeaserNavi').remove();
			} else { // if there is no cmpDynTeaserListe try to get all cmpBildTextStandard-components
				var seiteninhalt = $('#seiteninhalt'),
					pages_elements = seiteninhalt.children('.cmpBildTextStandard'),
					pages_elements_count = pages_elements.length,
					elements_per_page = 8;
				if (pages_elements_count > elements_per_page) {
					this.wrapper = $('<div></div>');
					this.wrapper.css({
						width: '590px',
						margin: '0 0 20px 0'
					});
					this.pages = [];
					var current_page = -1;
					for (var i = 0; i < pages_elements_count; i++) {
						if (i % elements_per_page === 0) {
							this.pages.push($('<div></div>').hide());
							current_page = current_page + 1;
							this.wrapper.append($(this.pages[current_page]));
						}
						$(this.pages[current_page]).append($(pages_elements[i]).clone());
						$(pages_elements[i]).hide();
					}
					pages_elements.remove();
					$(this.pages[0]).show();
					this.pages_count = this.pages.length;
					seiteninhalt.prepend(this.wrapper);
				}
			}
			
			// build pager
			if (this.pages_count > 1) {
				this.active_page_element = this.paging_html.find('.overview .active_page');
				// paging box
				this.pagingbox = this.paging_html.children('.pagingbox');
				this.pagingbox.children('.next').text(this.get_area_link_text).click(function(e){
					e.preventDefault();
					self.set_active_page(self.active + 1);
				});
				this.pagingbox.children('.prev').click(function(e){
					e.preventDefault();
					self.set_active_page(self.active - 1);
				});
				
				// browse box
				this.browsebox = this.paging_html.children('.browsebox');
				this.browsebox.find('.overview .pages_count').text(((this.pages_count > 5) ? '5' : this.pages_count)	);
				this.browsebox.find('.page_links').append(this.create_page_links());
				
				this.paging_html.find('.more a').text(this.get_area_link_text());
				this.page_links = this.paging_html.find('.page_links a').click(function(e){
					e.preventDefault();
					self.set_active_page(parseInt($(this).attr('rel')));
				});
				
				// more box
				this.morebox = this.paging_html.children('.morebox');
				this.morebox.children('.next').text(this.get_area_link_text).click(function(e){
					e.preventDefault();
					self.set_active_page(self.active + 1);
				});
				this.morebox.children('.prev').click(function(e){
					e.preventDefault();
					self.set_active_page(self.active - 1);
				});
				this.wrapper.append(this.paging_html);
				this.update_view();
			}
			
			if ($.url.param('dynpage')) {
				var dynpage = parseInt($.url.param('dynpage'), 10);
				if (dynpage < this.pages_count) {
					this.set_active_page(dynpage);
				}
			}
		},

		create_page_links: function() {
			var i = 0,
				page_links = '';
			for (i = 0; i < this.pages_count; i++) {
				if (i < this.max_page_links) {
					page_links += '<a href="#" rel="' + i + '">' + (i + 1) + '</a> ';
				}
			}
			return page_links;
		},

		set_active_page: function(new_index) {
			new_index = (new_index === this.pages_count) ? this.active : new_index;
			new_index = (new_index < 0) ? this.active : new_index;
			if (new_index !== this.active) {
				$(this.pages[this.active]).hide();
				$(this.pages[new_index]).show();
				this.active = new_index;
				this.update_view();
			}
		},

		update_view: function() {
			if (this.active < this.max_page_links) {
				this.page_links.removeClass('active');
				$(this.page_links[this.active]).addClass('active');
				this.browsebox.show();
				this.pagingbox.hide();
				this.morebox.show();
			} else {
				this.browsebox.hide();
				this.pagingbox.show();
				this.morebox.hide();
			}
			if (this.active === 0) {
				this.morebox.addClass('begin');
				this.pagingbox.addClass('begin');
			} else {
				this.morebox.removeClass('begin');
				this.pagingbox.removeClass('begin');
			}
			if (this.active === this.pages_count - 1) {
				this.morebox.addClass('end');
				this.pagingbox.addClass('end');
			} else {
				this.morebox.removeClass('end');
				this.pagingbox.removeClass('end');
			}
			
			this.active_page_element.text(this.active + 1);
		},

		get_area_link_text: function() {
			var link_text = 'Weiter',
				site_area = site_operator.get_area();

			if (site_area !== false) {
				
				link_text = (site_area === "resource-nachrichten" || site_area === 'resource-alle_nachrichten') ? 'Weitere Nachrichten' :
							(site_area === "resource-top_themen") ? 'Weitere Top-Themen' :
							(site_area === "resource-checklisten") ? 'Weitere Checklisten' :
							(site_area === "resource-buchtipps") ? 'Weitere Buchtipps' :
							(site_area === "resource-downloads") ? 'Weitere Downloads' :
							(site_area === "resource-links") ? 'Weitere Links' : 'Weiter';
			}
			//  iframe
			if (link_text === 'Weiter' && document_body.hasClass('is-top-thema')) {
				link_text = 'Weitere Top-Themen';
			} else if (link_text === 'Weiter' && document_body.hasClass('ebene-iframe')) {
				link_text = 'Weitere Nachrichten';
			}
			
			return link_text;
		}
	};

	if (is_edit_mode === false) {
		paging.init();
		(function(){
			var lists = $('.cmpDynTeaserListe'),
				window_url = window.location.href.split('?')[0];
			lists.each(function(){
				$(this).find('.teaserListe').each(function(index) {
					var links = $(this).find('.moreinfo a'),
						links_length = links.length,
						i, link;
					for (i = 0; i < links_length; i++) {
						link = links[i]
						link.href = link.href + '?dynpage='+index + '&dynurl=' + encodeURIComponent(window_url);
					}
				});
			});
		})();
	}
	
	// check the page type
	// ===================
	if ($('body').hasClass('standard')) {
		
		// change text of searchresult links
		if (site_operator.get_area() === "resource-suchergebnisse") {
			$('#content').find('.cmpSuchText .moreinfo').css('display', 'inline');
			$('#content').find('.cmpSuchText .moreinfo a').text('mehr');
		}
		
		// remove emtpy aktionskanal boxes
		// ===================
		if (is_edit_mode === false) {
			var ak_boxes = $('#aktionskanal > div'),
				ak_boxes_length = ak_boxes.length;
			ak_boxes.each(function(){
				var box = $(this);
				if (!box.hasClass('aktend') && box.children().length === 0) {
					box.remove();
					ak_boxes_length = ak_boxes_length - 1;
				}
			});
			if (ak_boxes_length === 1) {
				ak_boxes.remove();
			}
		}
		
		// generate grey box with head- and subheadline
		// ============================================
		var menu_item_level_1_name 		= '',
			menu_item_level_2_name 		= '',
			navpath_links = $('#navpath li a');
		
		if (navpath_links.length > 1) {
			menu_item_level_1_name = '<div id="section_title">' + $(navpath_links[1]).text() + '</div>';
		}
		if (navpath_links.length > 2) {
			if ($(navpath_links[1]).text() !== $(navpath_links[2]).text()) {
				menu_item_level_2_name = '<div id="sub_section_title">' + $(navpath_links[2]).text() + '</div>';
			}
		}
		
		
		menu_item_level_1_name = (menu_item_level_1_name === '') ? $('#navpath li:last a').text() : menu_item_level_1_name;
		$('<div id="content_head">' + menu_item_level_1_name + menu_item_level_2_name + '<div class="clearing"></div></div>').prependTo('#content');

		// add a history back-link + next detail item link
		// ===============================================
		var site_area = site_operator.get_area();
		if (site_area !== false && site_area !== 'resource-top_themen' && site_area !== 'resource-termine' && site_operator.is_detail_page()) {
			var next_item_href = site_operator.get_next_detail_item(),
				link_next = '';

			if (next_item_href !== false) {
				if (site_area == "resource-nachrichten"){ link_next = '<a href="'+ next_item_href +'" class="link_next">zur nächsten Nachricht</a>'; }
				if (site_area == "resource-checklisten"){ link_next = '<a href="'+ next_item_href +'" class="link_next">zur nächsten Checkliste</a>'; }
				if (site_area == "resource-buchtipps"){ link_next = '<a href="'+ next_item_href +'" class="link_next">zum nächsten Buchtipp</a>'; }
				if (site_area == "resource-downloads"){ link_next = '<a href="'+ next_item_href +'" class="link_next">zum nächsten Download</a>'; }
			}
			if ($.url.param('dynpage') && $.url.param('dynurl')) {
				$('.cmpUeberschriftStandard, .cmpUeberschriftTeaser').before('<a href="'+decodeURIComponent($.url.param('dynurl'))+'?dynpage=' + $.url.param('dynpage') +'" class="link_back">zurück</a> ' + link_next);
			} else {
				$('.cmpUeberschriftStandard, .cmpUeberschriftTeaser').before('<a href="javascript:history.back()" class="link_back">zurück</a> ' + link_next);
			}
		}
		
		// home page - move all TEXT/IMAGE-components to the content-head 
		// ==============================================================
		var home_bildtext = $('#resource-home .cmpBildTextStandard');
		if (is_edit_mode === false && home_bildtext.length) {
			$('#content_head').empty().prepend(home_bildtext);
		}

		// 	move the headline for special pages into the grey header box
		// =============================================================
		var page_headline = $('#resource-newsletter, #resource-rss, #resource-presse, #resource-wir_ueber_uns, #resource-termine').find('#content > .cmpUeberschriftStandard > .headline');
		if (is_edit_mode === false && page_headline.length) {
			$('#content_head').empty().prepend(page_headline);
		}

		/*if (is_edit_mode === false && document_body.attr('id').indexOf('Bestaetigungsseite') !== -1) {
			$('#content_head').empty().prepend($('.cmpUeberschriftStandard .headline'));
		}*/

		// add "rss"-class for styling
		// ===========================
		$('#aktionskanal .textlink a[href$="rss.html"]').parents('ul').addClass('rss');
		
		// add print-button on detailpages
		// ===============================
		if (site_operator.is_detail_page()) {
			// generate url for print-popup-version
			var print_url = window.location.href.split('?')[0].replace(/.html/g, ".popup.html?action=print");
			
			// set print event
			$('<a href="'+ print_url +'" class="print">Drucken</a>').prependTo('#footer_links').click(function(event) {
				event.preventDefault();
				window.open(this.href,'_blank','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=625,height=625,left=100,top=50');
			});
		}
		
		// add grey separtor line on "Top-Thema"-detail pages
		// ==================================================
		if (site_operator.get_area() == 'resource-top_themen' && site_operator.is_detail_page()) {
			var dynpage = $.url.param('dynpage'),
				page_links = $('.cmpLinkbox a[title="_next_page"], .cmpLinkbox a[title="_previous_page"]');
			if (dynpage) {
				page_links.each(function() {
					this.href = this.href + ((this.href.indexOf('?') === -1) ? '?' : '&') + 'dynpage=' + dynpage;
				});
			}
			page_links.parents('.cmpLinkbox').addClass('bisAktionskanal trenner');
		}
		
		// add back button and move next button on termin-detail-pages
		// ===========================================================
		if (!is_edit_mode && navpath_links.length > 1 && $(navpath_links[1]).hasClass('resource-termine') && site_operator.get_area() !== 'resource-termine') {
			var next_page_link = $('.cmpLinkbox a[title="_next_page"]'),
				content = $('#content_head');
			if (next_page_link.length) {
				var lb = next_page_link.parents('.cmpLinkbox').first().remove();
				next_page_link = next_page_link.last().css({'margin-left': 20});
				content.after(next_page_link);
				
			}
			content.after($('<a href="javascript:history.back()" class="link_back">zurück</a>'));
		}


	} else if ( $('body').hasClass('detail') ) {

		var iframe_url = false,
			iframe_url_read = false;

		if (is_iframe && document_body.hasClass('ebene-iframe')) {
			iframe_url = encodeURIComponent(window.location.href);
		} else if (is_iframe) {
			iframe_url_read = decodeURIComponent($.url.param('iframe_url'));
		}

		// open next/previous article as popup
		// ===================================
		if (!is_edit_mode && site_operator.is_detail_page()) {
			$('.cmpLinkbox a[title="_next_page"], .cmpLinkbox a[title="_previous_page"]').each(function(){
				var link = $(this),
					new_href = link.attr('href').replace('.html', '.popup.html');
				if (no_back_link) {
					new_href = new_href + '?nobacklink=true';
				}
				link.attr('href', new_href);
			})
		}

		// add print link for all detail pages
		// add close window link for detail pages which are not in an iframe
		if (site_operator.is_detail_page() && !is_iframe) {
			if (!is_print_mode) {
				$('<a href="#" class="print" onclick="window.print(); return false;">Drucken</a>').appendTo('#footer_links');
			}
			$('<a href="#" class="close_window" onclick="window.close();">Fenster schließen</a>').appendTo('#footer_links');
		} else if (is_iframe) {
			$('#footer_links').hide();
		}

		// add a history back-link
		// (only on detailpages and not iframe)
		// ====================================
		if (!document_body.hasClass('ebene-iframe') && site_operator.is_detail_page() && no_back_link === false) {
			var back_link_text = (is_iframe) ? 'zur Übersicht' : 'zurück',
				back_href = (iframe_url_read) ? iframe_url_read : 'javascript:history.back()',
				page_content = $('#content');
			if (iframe_url_read) {
				$.ajax(iframe_url_read, {
					dataType: 'html',
					type: 'GET',
					success: function(response) {
						var content = $(response);
						if (content.length) {
							var teaser_links = content.find('.cmpDynTeaserListe .moreinfo a'),
								teaser_links_length = teaser_links.length,
								location_href = window.location.href;
							if (teaser_links_length) {
								var teaser = null;
								for (var i = teaser_links_length-1; i >= 0; i--) {
									var link = teaser_links[i];
									link.href = link.href.replace('.html', '.popup.html');
									if (location_href.indexOf(link.href) !== -1 ) {
										teaser = i;
									}
								}
								if (teaser !== null && teaser !== 0) {
									var next_href = teaser_links[teaser - 1].href + '?iframe_url=' + encodeURIComponent(iframe_url_read);
									page_content.prepend($('<a href="' + next_href + '" class="link_next">zur nächsten Nachricht</a>'));
								} else {
									page_content.prepend($('<a href="' + back_href + '" class="link_next">' + back_link_text + '</a>'));
								}
								if (teaser !== null && teaser !== teaser_links_length-1) {
									var prev_href = teaser_links[teaser + 1].href + '?iframe_url=' + encodeURIComponent(iframe_url_read);
									page_content.prepend($('<a href="' + prev_href + '" class="link_back">zurück</a>'));
								} else {
									page_content.prepend($('<a href="' + back_href + '" class="link_back">' + back_link_text + '</a>'));
								}
							}
						} else {
							page_content.prepend($('<a href="' + back_href + '" class="link_back">' + back_link_text + '</a>'));
						}
					}
				});
			} else {
				page_content.prepend($('<a href="' + back_href + '" class="link_back">' + back_link_text + '</a>'));
			}
		}

		// Dynamische Teaserliste im Popup
		// ===============================		
		var dyn_teaser = $('.cmpDynTeaserListe'),
			is_top_thema = (document_body.attr('id').indexOf('top_thema') !== -1 || document_body.attr('id').indexOf('top_themen') !== -1) ? true : false;
		if (dyn_teaser.length) {
			dyn_teaser.each(function(){
				var wrapper = $(this),
					lists_objs = [],
					lists, div_elements, pointer;
				wrapper.find('.clear ').detach();
				lists = wrapper.children('div[id*="_render_"]');
				lists.each(function(i){
					lists_objs[i] = {
						list: $(this),
						count: $(this).children('.cmpBildTextTeaser').length
					};
				});
				div_elements = wrapper.find('.cmpBildTextTeaser').detach();
				pointer = div_elements.length - 1;
				div_elements.find('.moreinfo a').each(function() {
					var link = this,
						new_href = link.href.replace('.html', '.popup.html');
					if (is_iframe && iframe_url) {
						new_href = new_href + ((new_href.indexOf('?') === -1) ? '?' : '&') + 'iframe_url=' + encodeURIComponent(iframe_url);
					}
					if (is_top_thema && is_iframe) {
						new_href = new_href + ((new_href.indexOf('?') === -1) ? '?' : '&') + 'nobacklink=true';
					}
					link.href = new_href;
				});
				
				lists.each(function(index){
					for (var i = 0; i < lists_objs[index].count; i++) {
						lists_objs[index].list.append($(div_elements[pointer]));
						pointer--;
					}
					lists_objs[index].list.children('.TeaserNavi ').detach().appendTo(lists_objs[index].list);
				});
			});
		}
	
		// Linkbox im Popup - hide internal links
		// ======================================	
		var linkboxes = $('.cmpLinkbox'),
			saved_iframe_url = (document_body.hasClass('ebene-iframe')) ? null : iframe_url_read;
		if (linkboxes.length) {
			linkboxes.each(function(){
				var lb = $(this),
					links = lb.find('.textlink a'),
					links_length = links.length,
					hidden_count = 0;
				for (var i = 0; i < links_length; i++) {
					var link = $(links[i]),
						href = link.attr('href');
					if (link.attr('title') === '_next_page' || link.attr('title') === '_previous_page' || 
						(href.indexOf('www') === 0 || href.indexOf('http://') === 0) &&
						href.indexOf(window.location.host) === -1) {
							link.parents('li').first().css('display', 'block');
					} else {
						link.parents('li').first().detach();
						hidden_count = hidden_count + 1;
					}
					if (saved_iframe_url && (link.attr('title') === '_next_page' || link.attr('title') === '_previous_page')) {
						var new_href = (no_back_link) ? '&' : '?';
						new_href = link.attr('href') + new_href + 'iframe_url=' + encodeURIComponent(saved_iframe_url);
						link.attr('href', new_href);
					}
					if (saved_iframe_url && link.attr('title') === '_next_page' && link.children('span').text() == 'zur Übersicht') {
						link.attr('href', decodeURIComponent(saved_iframe_url));
					}
				}
				// hide link box completly when all links are hidden
				if (hidden_count === links_length) {
					lb.detach();
				}
			});
		}

		// Neuer Footer
		// ============
		if ($.url.param('action') !== 'print') {
			var text = (document_body.attr('id') === 'resource-top_themen') ? '' : 'redaktionell verantwortlich',
				popup_foot = $('<div class="popup_footer">' + text + '<img src="/content/dam/f0906-0/individualisierung/internet/layout/images/logo_footer_webbank.jpg" alt="Mittelstanddirekt" /><div>');
			$('#content').append(popup_foot);
		}

		// Druckansicht
		// ============
		if (is_print_mode) {
			document_body.addClass('print');
			var content_footer_html = '<div class="offer_from"><span>MittelstandDirekt.de ist ein Angebot der</span><img src="/content/dam/f0906-0/individualisierung/internet/layout/images/logo_vr_drucken.jpg" alt=" "/></div><div class="copyright">© VR-NetWorld GmbH</div>';
			$('#content').append('<div id="content_footer">' + content_footer_html + '</div>');

			var print_header = $('body.print #header');
			if (print_header.length) {
				print_header.css('background', 'transparent none');
				var print_logo = $('<img src="" alt="Mittelstanddirekt - Volskbanken Raiffeisenbanken"/>');
				print_logo.attr('src', '/content/dam/f0906-0/individualisierung/internet/layout/images/mittelstand_direkt_logo_print.png');
				print_logo.css({
					'top': 0,
					'right': 0,
					'bottom': 'auto',
					'left': 'auto'
				});
				var banklogo = print_header.find('#banklogo');
				banklogo.height(50).empty().append(print_logo);
			}
			if ($('#content').find('a[title=_next_page]').length) {
				new BuildTopThemaForPrint();
			} else {
				window.print();
			}
		}

	}
	
	
	// hide the ul when li is hidden
	// =============================	
	$('#bedarfsnavi ul li').each(function() {
		var li_element = $(this);
		if (li_element.is(':hidden')) {
			li_element.parent().hide();
		}
		if (li_element.hasClass('navtopic1onselect')) {
			$('.cmpDynTeaserListe').addClass('borderlize');
		}
	});
	
	// homepage - add class to teaserlist
	// ==================================
	$('#resource-home .cmpDynTeaserListe').addClass('borderlize');
	
	// set css classes für special links/linkslists
	// ============================================
	$('.linkbox .textlink a[title*="_leseprobe"]').parents('li').addClass('leseprobe');
	$('.linkbox .textlink a[title*="_autor"]').parents('li').addClass('autor');
	$('.linkbox .textlink a[title*="_amazon"]').parents('li').addClass('amazon');
	$('.linkbox .textlink a[title*="_next_page"]').parents('li').addClass('next_page');
	$('.linkbox .textlink a[title*="_previous_page"]').parents('li').addClass('previous_page');
	
	// split teaser-headlines
	// ======================
	$('.cmpBildTextTeaser').each(function(){
		var teaser_headline_elem	= $(this).find('.headline h2'),
			teaser_headline_raw 	= teaser_headline_elem.text(),
			teaser_headline			= '',
			teaser_subheadnline		= '',
			headline_array			= [];
		
		if (teaser_headline_raw != '' && teaser_headline_raw.search("\\:") != -1) {
			headline_array 	= teaser_headline_raw.split(': ');
			teaser_headline 	= headline_array[1];
			teaser_subheadnline = '<h4>'+headline_array[0]+'</h4>';
			teaser_headline_elem.text(teaser_headline).before(teaser_subheadnline);
		}		
		$(this).find('.content').prepend($(this).find('.headline'));
	});
	
	// remove "weiter"-links from teaserlists on landing-pages
	// =======================================================
	if (is_edit_mode === false && (site_operator.is_rubric_start_page() || document_body.attr('id') === 'resource-home')) {
		$('.TeaserNavi').remove();
		var rubic_dyn_teaser_navi = $('.cmpDynTeaserListe');
		if (rubic_dyn_teaser_navi.length) {
			var rubic_linkbox = rubic_dyn_teaser_navi.next('.cmpLinkbox');
			if (rubic_linkbox.length){
				rubic_linkbox.appendTo(rubic_dyn_teaser_navi);
				rubic_linkbox.children('.linkbox').css({
					padding: '20px 0 10px 0',
					margin: 0
				});
			}
		}
	}
	

	// build banksearch
	//=================	
	var bank_search = {},
		requiredMajorVersion = 9,
		requiredMinorVersion = 0,
		requiredRevision = 16;

	function getBankSearchLayer(city) {
		var hasProductInstall = DetectFlashVer(6, 0, 65),
			hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	
		if ( hasProductInstall && !hasRequestedVersion ) {
			// DO NOT MODIFY THE FOLLOWING FOUR LINES
			// Location visited after installation is complete if installation is required
			var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
			var MMredirectURL = window.location;
			document.title = document.title.slice(0, 47) + " - Flash Player Installation";
			var MMdoctitle = document.title;	
			var obj_str = AC_FL_RunContent(
				"src", "/content/dam/f0906-0/content/bankensuche/playerProductInstall",
				"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
				"width", "602",
				"height", "627",
				"align", "middle",
				"id", "AddressFinder",
				"quality", "high",
				"bgcolor", "#ffffff",
				"name", "AccountCreator_vr",
				"allowScriptAccess","sameDomain",
				"type", "application/x-shockwave-flash",
				"pluginspage", "http://www.adobe.com/go/getflashplayer"
			);
			
			new Lightbox({
				'class_name': 'bank_search_layer',
				'header': $('<h2>Filialsuche</h2>'),
				'content': $(obj_str)
			});
		} else if (hasRequestedVersion) {
			// if we've detected an acceptable version
			// embed the Flash Content SWF when all tests are passed
	
			var flashVars = 'city=' + city + '&begriff=62&ID62';
	
			var obj_str = AC_FL_RunContent(
				"src", "/content/dam/f0906-0/content/bankensuche/addressfinder-flex3-mittelstanddirekt-3.8.8",
				"width", "602",
				"height", "627",
				"align", "middle",
				"id", "AddressFinder",
				"quality", "high",
				"wmode", "transparent",
				"name", "AccountCreator_vr",
				"allowScriptAccess","sameDomain",
				"type", "application/x-shockwave-flash",
				"flashvars",flashVars,
				"pluginspage", "http://www.adobe.com/go/getflashplayer"
			);
			
			new Lightbox({
				'class_name': 'bank_search_layer',
				'header': $('<h2>Filialsuche</h2>'),
				'content': $(obj_str),
				'close_callback': function() {
					try {
						_etc2_(et_pagename);
					} catch (e) {}
				}
			});
			try {
				ET_Event.click('Bankensuche');
				_etc_2('Bankensuche - ' + et_pagename);
			} catch (e) {}
		} else {
			// flash is too old or we can't detect the plugin
			var alternateContent = 'Diese Anwendung ben&ouml;tigt einen FlashPlayer. Bitte laden Sie eine aktuelle Version'
				  + '<a href="http://www.adobe.com/go/getflashplayer">'
				  + '<Image src="assets/get_adobe_flash_player.png" />'
				  + '</a>';
			new Lightbox({
				'class_name': 'bank_search_layer',
				'header': $('<h2>Filialsuche</h2>'),
				'content': $(alternateContent)
			});
		}
	}

	bank_search.search_element = $('#seiteninhalt p:contains("###bankensuche###")');
	bank_search.ak_element = $('#aktionskanal');
	bank_search.ak_element_head = $('<div class="akthead"><img src="/content/dam/f0906-0/individualisierung/internet/layout/images/icon_02.gif" alt="" border="0" width="18" height="18"><div class="headline">Kontakt</div></div>');
	bank_search.ak_element_wrapper = $('<div class="aktvar2"></div>').append(bank_search.ak_element_head);
	bank_search.form = $('<form action="#" method="get" class="banksearch"></form>');
	bank_search.form_ak = $('<form action="#" method="get" class="banksearch"></form>');
	bank_search.h3 = $('<h3>Mehr erfahren:</h3>');
	bank_search.text = $('<p>Sie haben Fragen zum Thema Geschäftsform?<br/>Ihre Volksbank/Raiffeisenbank vor Ort berät sie gern</p>');
	bank_search.label = $('<label>Meine Bank</label>');
	bank_search.input = $('<input class="text" type="text" name="search" value=""/>');
	bank_search.input_ak = $('<input class="text" type="text" name="search" value=""/>');
	bank_search.submit = $('<input class="submit" type="submit" value="Suchen"/>');	
	bank_search.form.append(bank_search.h3).append(bank_search.text).append(bank_search.label).append(bank_search.input).append(bank_search.submit);
	
	if (bank_search.search_element.length) {
		if (is_iframe === false) {
			bank_search.form.bind('submit', function(e){
				e.preventDefault();
				getBankSearchLayer(bank_search.input.val());
			});
			bank_search.search_element = bank_search.search_element.parents('.cmpBildTextStandard:first');
			bank_search.search_element.replaceWith(bank_search.form);
			bank_search.input.val('PLZ/Ort');
			bank_search.input.bind('focus', function(){
				if (bank_search.input_ak.val() === 'PLZ/Ort') {
					bank_search.input_ak.val('');
				}
			}).bind('blur', function(){
				if (bank_search.input.val() === '') {
					bank_search.input.val('PLZ/Ort');
				}
			});
		} else if (is_iframe === true) {
			bank_search.search_element.parents('.cmpBildTextStandard:first').remove();
		}
	}

	bank_search.form_ak.append(bank_search.label.clone()).append(bank_search.input_ak).append(bank_search.submit.clone());
	if (site_operator.get_area() !== "resource-kontakt" &&
		site_operator.get_area() !== "resource-kontakt_unique_relations" &&
		document_body.attr('id') !== 'resource-Bestaetigungsseite_Kontakt') {
		
		bank_search.ak_element_wrapper.append(bank_search.form_ak);
		if (bank_search.ak_element.length) {
			bank_search.form_ak.bind('submit', function(e){
				e.preventDefault();
				getBankSearchLayer(bank_search.input_ak.val());
			});
			bank_search.ak_element.append(bank_search.ak_element_wrapper);
			var aktend = bank_search.ak_element.children('.aktend');
			if (aktend.length) {
				bank_search.ak_element.append(aktend);
			} else {
				bank_search.ak_element.append($('<div class="aktend"></div>'));
			}
			bank_search.input_ak.val('PLZ/Ort');
			bank_search.input_ak.bind('focus', function(){
				if (bank_search.input_ak.val() === 'PLZ/Ort') {
					bank_search.input_ak.val('');
				}
			}).bind('blur', function(){
				if (bank_search.input_ak.val() === '') {
					bank_search.input_ak.val('PLZ/Ort');
				}
			});
		}
	}
	// ------------------------------------------------------------------------------------------
	
	// sort iframe news
	if(url.search('iframe') > -1 && url.search('dyn') > -1 && url.search('nachrichten') > -1){
		sortTeasersByDate();
	}
		
});

// set the caption and copyright under the image
// (wait until the window including images are loaded => webkit browser)
// =====================================================================
$(window).load(function() {
	$('.cmpBildTextStandard .image img[title!=""]').each(function(){
		var img_caption		= '';
		var img_copyright	= '';
		var img_title 		= $(this).attr('title');
		var img_width		= $(this).width();
		
		// check if separator is exist
		if (img_title.search("\\|") != -1) {
			var title_array = img_title.split(' | ');
			img_caption 	= '<span class="img_caption">'+title_array[0]+'</span>';
			img_copyright 	= '<span class="img_copyright">'+title_array[1]+'</span>';
		} else {
			img_caption = '<span class="img_caption">'+img_title+'</span>';
		}
		$(this).parents('.image').css({width: img_width}).append(img_caption + ' ' + img_copyright);
		
		// check whether the text wraps (one line or more?)
		if ($('.img_copyright').height() > 14) {
			$('.img_copyright').addClass('block');
		}
	});
});


var site_operator =  {
	
	// get resource of element	
	get_resource: function(menu_item) {
		if (menu_item && menu_item.size() === 1) {
			var classes = menu_item.attr('class').split(' '),
				resource = false;
			$(classes).each(function(){
				if (this.toString().match(/resource-/) !== null) {
					resource = this.toString();
				}
			});
			if (resource !== false) {
				return resource;
			}
		}
		return false;
	},
	
	// get resource of current area
	get_area: function() {
		var links = $('#navpath a'),
			area = false;

		if (links.length >= 3) {
			area = this.get_resource($(links[2]));
		} else if (links.length <= 2) {
			area = this.get_resource($(links[1]));
		}
		return area;
	},
	
	is_rubric_start_page: function() {
		if ($('.navtopic1onselect').size() === 1) {
			return true;
		}
		return false;
	},
	
	is_top_thema: function() {
		var is_top_thema = false,
			document_body = $(document.body);

		// test for ID
		if ($('#resource-top_themen').length > 0) {
			is_top_thema = true;
		}

		// test navpath
		if (is_top_thema === false) {
			var nav_path_links = $('#navpath a'),
				nav_path_length = nav_path_links.length;
			for (var i = 0; i < nav_path_length; i++) {
				if ($(nav_path_links[i]).hasClass('resource-top_themen')) {
					is_top_thema = true;
				}
			}
		}

		// test iframe
		if (is_top_thema === false && document_body.hasClass('ebene-iframe')) {
			if (document_body.attr('id').indexOf('msd_top_thema') !== -1 || document_body.attr('id').indexOf('msd_top_themen') !== -1) {
				is_top_thema = true;
			}
		}

		if (is_top_thema === true) {
			document_body.addClass('is-top-thema');
		}
	},
	
	is_detail_page: function() {
		if ( $('body').hasClass('detail') ) {
			if ($('.cmpDynTeaserListe').length === 0 && $('#resource-links').length === 0 && $('#resource-checklisten').length === 0) {
				return true;
			}
		} else {
			if ($('.cmpDynTeaserListe').length === 0 && $('#navpath a').length > 3) {
				return true;
			}
		}
		return false;
	},
	
	get_next_detail_item: function() {
		var selector = $('.navtopic3onselect');
		if (selector.length > 0) {
			var id_parts = selector.attr('id').split('-'),
				next_id, next_list_item;
			id_parts[id_parts.length-1] = parseInt(id_parts[id_parts.length-1]) + 1;
			next_id = id_parts.join('-');
			next_list_item = $('#'+next_id);
			
			if (next_list_item.size() === 1) {
				return next_list_item.find('a').attr('href');
			}
		}
		return false;
	},
	
	switchDynTeaserListe : function(dyn_teaser, popup) {
		var wrapper = dyn_teaser,
			is_top_thema = ($(document.body).attr('id').indexOf('top_thema') !== -1 || $(document.body).attr('id').indexOf('top_themen') !== -1) ? true : false,
			lists_objs = [],
			lists, div_elements, pointer,
			popup = (popup) ? true : popup;
		
		wrapper.find('.clear ').detach();
		lists = wrapper.children('div[id*="_render_"]');
		lists.each(function(i){
			lists_objs[i] = {
				list: $(this),
				count: $(this).children('.cmpBildTextTeaser').length
			};
		});
		div_elements = wrapper.find('.cmpBildTextTeaser').detach();
		pointer = div_elements.length - 1;
		div_elements.find('.moreinfo a').each(function() {
			var link = $(this),
				new_href = link.attr('href');
			if (popup === true) {
				new_href = new_href.replace('.html', '.popup.html');
			}
			if (is_top_thema && is_iframe) {
				new_href = new_href + '?nobacklink=true';
			}
			link.attr('href', new_href);
		});
		
		lists.each(function(index){
			for (var i = 0; i < lists_objs[index].count; i++) {
				lists_objs[index].list.append($(div_elements[pointer]));
				pointer--;
			}
			lists_objs[index].list.children('.TeaserNavi ').detach().appendTo(lists_objs[index].list);
		});
	}
};

// prevent piwik call, call it on document ready instead
document.write_ = document.write;
document.write = function(html) {
	if(html.search(/piwik.js/i) == -1){
		document.write_(html);
	} else {
		$(document).ready(function(){
			$.getScript($(html).attr('src'));
			try {
				piwik_log(piwik_action_name, piwik_idsite, piwik_url);
			} catch (e) {
			}
		});
	}
}
