var ALLOW_FALLBACK = false;

// Guarantee that often queried soi variables
// and soi_Tagwriter are defined.
if (window.add2tag == null) var add2tag = '';
if (window.soi_adtrace == null) var soi_adtrace = '';
if (window.soi_ad == null) var soi_ad = '';
if (!window.soi_Tagwriter) window.soi_Tagwriter = function() {return '';}


/* GOOGLE ADS CONFIG */

/*
	This object allows google ads to query the state of relevant ordinary ads.
	It does *not* provide full info on display of ordinary ads.
	Key/value pairs ad_id => 0|1 are set by checkRectangle (e.g. rectangle2: 1).
	Thus SIM_ADTAG_INFO must only be queried after execution of these functions.
*/
var SIM_ADTAG_INFO = {};

// This variable is needed for incrementing google_skip
var SIM_GOOGLE_COUNT = 0;

// This variable is set with google variable configuration
// before including google's show_ads.js
var SIM_GOOGLE_ADTYPE = '';

/**********************************/

function existsRectangle(ad_id) {
	var existsTest = new RegExp(ad_id, 'i');
	var exists = existsTest.test(window.soi_adtrace);

	var fallback;

	if (ALLOW_FALLBACK) {
		fallback = false;
	}
	else {
		var fallbackTest = new RegExp(ad_id + '.+Fallback', 'i');
		fallback = fallbackTest.test(window.soi_adtrace);
	}

	return exists && !fallback ? true : false;
}

function hasBlockpixel(ad_id) {
	var blockpixelTest = new RegExp(ad_id + '.+Block[_-]?pixel', 'i');
	var blockpixel = blockpixelTest.test(window.soi_adtrace);
	return blockpixel ? true : false;
}

function reserveSowefoSpace(ad_id) {
	var sowefoSpaceTest = new RegExp(ad_id + '.+Block[_-]?pixel.+' + ad_id, 'i');
	var display = sowefoSpaceTest.test(window.soi_adtrace);
	// fullbanner2 keyword can also be 'superblock'
	if (!display && ad_id == 'fullbanner2') {
		sowefoSpaceTest = new RegExp(ad_id + '.+Block[_-]?pixel.+' + 'superblock', 'i');
		display = sowefoSpaceTest.test(window.soi_adtrace);
	}
	return display ? true : false;
}

function isType(ad_id, type, adtrace) {
	if (!adtrace) adtrace = window.soi_adtrace;
	if (!adtrace) return;

	var typeTest = new RegExp(ad_id + '.+' + type, 'i');
	var result = typeTest.test(adtrace);
	return result ? true : false;
}

function minWidthForSkyscraperOutside() {
	var searchstring = window.location.search.substring(1);

	var found;
	var min_width;

	if (searchstring) {
		found = searchstring.match(/outside=([0-9]+)/);
		if (found && found[1]) min_width = parseInt(found[1]);
	}
	
	if (!min_width) min_width = 1175;
	return min_width;
}

function checkRectangle(ad_id, div_id) {
	var exists = existsRectangle(ad_id) ? true : false;
	SIM_ADTAG_INFO[ad_id] = exists ? 1 : 0;

	// Container might not exist.
	var elem = document.getElementById(div_id);
	if (!elem) return exists;

	if (exists) {
		if (hasBlockpixel(ad_id)) {
			if (reserveSowefoSpace(ad_id)) {
				if (ad_id != 'fullbanner2') {
					elem.style.backgroundColor = 'transparent';
				}
				elem.style.backgroundImage = 'none';
				var td_elem = document.getElementById('td-' + ad_id);
				if (td_elem) td_elem.style.backgroundImage = 'none';
			}
			else {
				hideElementKabeleine(elem);
				return;
			}
		}

		adjustLayoutForBigbanner(window.soi_adtrace); 
		showElementKabeleine(elem);
	}
	else {
		hideElementKabeleine(elem);
	}

	return exists;
}

function adjustLayoutForBigbanner(adtrace) {
	if (!isType('fullbanner2', 'PB2', adtrace)) return;

	setAttributeForElement('head2', 'height', '240px');
	setAttributeForElement('head3', 'height', '240px');
	setAttributeForElement('head1', 'backgroundPosition', '1004px 224px');
	setAttributeForElement('head4', 'top', '224px');
	setAttributeForElement('fullbanner2', 'height', '190px');
}

function adjustLayoutForWallpaper() {
	void(0);
}

// Function may be called after loading popup1
function adjustLayoutForSowefo() {
	void(0);
}

function shiftSkyscraper(div_id) {
	var el = document.getElementById(div_id);
	if (!el) return;
	if (el.style.display == 'none') return;

	if (needsSkyscraperEmbedded()) {
		el.className = 'skyscraper-embedded';
	}

	window.pso_skyscraper_x = findPosX(el);
	window.pso_skyscraper_y = findPosY(el);
}

function needsSkyscraperEmbedded() {
	var self = arguments.callee;

	if (!self.__initialized) {
		self.__initialized = 1;

		if (!window.forceSkyscraperOutside) {
			if (window.forceSkyscraperInside) {
				self.needs_skyscraper_embedded = 1;
			}
			else if (!window.preferSkyscraperOutside
				&& !hasScreenWidthForSkyscraperOutside()) {
					self.needs_skyscraper_embedded = 1;
			}
		}
		
		if (!self.needs_skyscraper_embedded) self.needs_skyscraper_embedded = 0;
	}
	
	return self.needs_skyscraper_embedded;
}

function hasSkyscraperEmbedded() {
	return SIM_ADTAG_INFO['skyscraper1'] && needsSkyscraperEmbedded();
}

function hasScreenWidthForSkyscraperOutside()
{
	var screenwidth = window.innerWidth ?
		  window.innerWidth
		: document.all.tags("body")[0].offsetWidth;
	
	return screenwidth >= minWidthForSkyscraperOutside() ? true : false; 
}

function checkGalleryRectangle(ad_id, forwardUrl) {
    if (!existsRectangle(ad_id)) document.location = forwardUrl;
}

function checkCrossRectangles() {
	void(0);
}

/*
	Function for moving soi and google ads to final location
*/
function moveAd(id)
{
	var source_element = document.getElementById('source_' + id);
	var target_element = document.getElementById('target_' + id);

	if (!source_element || !target_element) return;
	
	var target_parent = target_element.parentNode;

	target_parent.replaceChild(source_element, target_element);
	source_element.style.display = source_element.tagName.toLowerCase() == 'div' ?
		'block' : 'inline';
}

/*
	Functions for reloading adtags in iframes. 
*/

function existsRectangleInIframe(ad_id, iframe_soi_adtrace) {
	if (iframe_soi_adtrace) {
		var existsTest = new RegExp(ad_id, 'i');
		var exists = existsTest.test(iframe_soi_adtrace);

		var fallback;
		
		if (ALLOW_FALLBACK) {
			fallback = false;
		}
		else {
			var fallbackTest = new RegExp(ad_id + '.+Fallback', 'i');
			fallback = fallbackTest.test(iframe_soi_adtrace);
		}

		return exists && !fallback ? true : false;
	}
	
	return false;
}

function checkRectangleInIframe(ad_id, div_id, iframe_soi_adtrace) {
	if (existsRectangleInIframe(ad_id, iframe_soi_adtrace)) {
		showElementKabeleine(document.getElementById(div_id));
		return 1;
	}
	else {
		hideElementKabeleine(document.getElementById(div_id));
		return;
	}
}

/*
	Usage:
	*******
	
	The function can be assigned to the onload event of an iframe.
	This will trigger the reload of adtags and ivw count (optionally)
	on each reload of this iframe.
	
	Arguments:
	**********
	
	- iframe_ids:
	  an array of iframe ids associated with iframes containing adtags
	  *or*
	  a string containing a single iframe id
	
	- iframe:
	  a reference to the iframe that triggers the function
	  (this iframe must have a unique id)
	  *or*
	  a string containing a unique id
	
	- do_ivw_count:
	  boolean value
	  If set to true, executes the function 'count_ivw' provided
	  this function is defined.
	  
	Please note:
	************
	
	- The function gets executed on reload of the master iframe,
	  but *not* on first load of the document.
	
	- In IE 5.0, iframes do not fire the onload event.
	  Thus, this function gets never called in IE5.0.
*/

function iframesReload(iframe_ids, iframe, do_ivw_count)
{
	var id = typeof(iframe) == 'object' ? iframe.getAttribute('id') : iframe;
	// Some default id.
	if (!id) id = 'null';
	
	// This prevents reloading of iframes on initial load of master document.
	if (iframesReload[id]) {
		if (do_ivw_count && window.count_ivw) {count_ivw();}
		if (iframe_ids) {
			if (typeof(iframe_ids) == 'string') {
				reloadIframe(iframe_ids, 0);
			}
			else {
				for (var i = 0; i < iframe_ids.length; i++) {
					reloadIframe(iframe_ids[i], i);
				}
			}
		}
	}
	else {
		iframesReload[id] = 1;
	}
}

function reloadIframe(iframe_id, counter)
{
	var element = document.getElementById(iframe_id);
	if (element) {
		var content_window = element.contentWindow;

		// contentWindow not working in IE 5.0.
		if (!content_window && document.frames) content_window = document.frames[iframe_id];

		if (content_window) {
			content_window.location.reload();
		}
		else {
			// contentWindow not working in NS6.
			// This seems not to be working either due to NS6 caching problems.
			var src = element.src;
			if (src) element.src = src;
		}
	}
}

function resizeIframe(iframe_id, ad_id, iframe_soi_adtrace, iframe_soi_dimension)
{
	if (iframe_soi_dimension) {
		var dimensions = iframe_soi_dimension[ad_id];
		if (dimensions) {
			var iframe = parent.document.getElementById(iframe_id);
			if (iframe) {
				var x = dimensions[0];
				// For some strange reason, the powerbanner height value
				// is usually faulty (90 instead of 180).
				var y = ad_id == 'fullbanner2' && isType('fullbanner2', 'PB2', iframe_soi_adtrace) ?
					180 : dimensions[1];

				iframe.style.width  = x ? x + 'px' : 0 + 'px';
				iframe.style.height = y ? y + 'px' : 0 + 'px';
			}
		}
	}
}

function handleIframe(iframe_window, iframe_soi_adtrace, iframe_soi_dimension)
{
	var ids = parseIframeQuery(iframe_window);
	var iframe_id = ids[0];
	var ad_id     = ids[1];
	var div_id    = ids[2];
	
	if (checkRectangleInIframe(ad_id, div_id, iframe_soi_adtrace)) {
		resizeIframe(iframe_id, ad_id, iframe_soi_adtrace, iframe_soi_dimension);
		adjustLayoutForBigbanner(iframe_soi_adtrace);
	}
	
	handleIframeSoiAdtrace(1, ad_id, iframe_soi_adtrace);
}

function parseIframeQuery(iframe_window)
{
	var searchstring = iframe_window.location.search;
	if (searchstring) {
		searchstring = searchstring.substring(1);
	}
	else {
		return ['', '', ''];
	}
	
	var found;

	var iframe_id = '';
	var ad_id  = '';
	var div_id = '';
	
	if (searchstring) {
		found = searchstring.match(/div_id=([^&]*)/);
		if (found && found[1]) div_id = found[1];
		found  = searchstring.match(/iframe_id=([^&]*)/);
		if (found && found[1]) iframe_id = found[1];
		found  = searchstring.match(/ad_id=([^&]*)/);
		if (found && found[1]) ad_id = found[1];
	}

	return [iframe_id, ad_id, div_id];
}

function handleIframeSoiAdtrace(mode, ad_id, iframe_soi_adtrace)
{
	if (!window.iframe_adtrace)
		window.iframe_adtrace = new Array;
	
	if (mode == 1) {
		var items = iframe_soi_adtrace.split('\n');
		// Last element is empty.
		var new_adtrace = items[items.length - 2];
		if (new_adtrace) window.iframe_adtrace[ad_id] = new_adtrace;
	}
	else {
		// This condition is met if called from within ad_iframe.php.
		// Thus 'parent'.
		var retval = '';
		if (parent.iframe_adtrace) {
			for (var value in parent.iframe_adtrace) {
				if (value != ad_id) retval = retval + parent.iframe_adtrace[value] + '\n';
			}
		}
		return retval;
	}
}


/***************************
Shopping tipps
****************************/

/*
	Usage:
	Functions must be called in *separate* script tags!
*/

function loadShoppingtipp(do_load) {
	// SOI variable
	if (!window.SOI_place) return;

	if (window.SOI_ZAHL == null) {
		window.SOI_ZAHL = 1;
	}
	else {
		window.SOI_ZAHL += 1;
	}

	// do_load argument may be set to false for debugging.
	// Value is passed in shoppingtipp template.
	if (!do_load) return;

	document.write(soi_Tagwriter(window.SOI_place[window.SOI_ZAHL], add2tag+"params.styles=img"));
}

function cross_shoptipp_197() {
	if (!window.SOI_ZAHL) return;

	if (window.SOI_ZAHL == 1) document.write('<div id="adtags-shop1" class="shoptipp-head">Shopping Tipp<\/div>');

	var tipp_exists = window.IMPERIA_PREVIEWMODE || existsRectangle('shoppingtipp' + window.SOI_ZAHL);

	if (tipp_exists) {
		var snippet =
			  '<div class="shoptipp-bg">'
			+ '<table border="0" cellspacing="0" cellpadding="0" class="align-top">'
			+ '<tr>'
			+ '<td style="width:65px"><a href="'+window.SOI_LNK+'" target="_blank"><img src="'+window.SOI_IMG+'" width="60" height="60" alt="" \/><\/a><br \/><\/td>'
			+ '<td style="width:127px"><h1><a href="'+window.SOI_LNK+'" target="_blank">'+window.SOI_TXT1+'<\/a><\/h1>'
			+ '<p>'+window.SOI_TXT2+'<\/p>'
			+ '<p><a href="'+window.SOI_LNK+'" class="tipplink" target="_blank">'+window.SOI_TXT3+'<\/a><\/p><\/td>'
			+ '<\/tr>'
			+ '<\/table>'
			+ '<\/div>'
			+ '<div class="shoptipp-spacer"><\/div>'
		document.write(snippet)
		setAttributeForElement('adtags-shop1', 'display', 'block');
	}
}

/***************************
Google Adsense
****************************/

/*
	This function is called from adtags*.class.php
	It loads the google script 'show_ads.js' dynamically if needed.
*/
function load_google_ads(type)
{
	if (type.match(/^rectangle2/)) {
		if (SIM_ADTAG_INFO['rectangle2']) return;
		
		if (type == 'rectangle2-contentvideo'
			&& hasSkyscraperEmbedded()) return;
	}
	else if (type == 'skyscraper') {
		// No depency on ordinary adtags
	}
	else if (type.match(/^fullbanner2/)) {
		if (SIM_ADTAG_INFO['fullbanner2']) return;
	}
	
		document.write('<script language="JavaScript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"><\/script>');
	
	
}

/*
	The function 'google_ad_request_done' is executed in
	http://pagead2.googlesyndication.com/pagead/show_ads.js
	Thus the function is not executed if load_google_ads returns,
	and existence checks for soi-ads is not required here.
*/
function google_ad_request_done(google_ads) {
	if (!google_ads || google_ads.length == 0) return;
	
	var type = SIM_GOOGLE_ADTYPE;

	if (type == 'rectangle2') {
		write_google_ads(google_ads, type);
	}
	else if (type == 'skyscraper') {
		write_google_ads(google_ads, type);
	}
	else if (type.match(/^fullbanner2/)) {
		write_google_ads_popup(google_ads, type);
	}
	else if (type == 'suchergebnisse') {
		write_google_suchergebnisse(google_ads);
		// No incrementing of google_skip
		return;
	}
	else {
		return;
	}

	if (google_ads[0].bidtype == "CPC" && google_ads[0].type != 'image') {
		SIM_GOOGLE_COUNT += google_ads.length;
	}

	return;
}

function write_google_ads(google_ads, type) {
	if (!google_ads || google_ads.length == 0) return;
	
	var s = '';
	
	if (type == 'rectangle2') {
		var i = 0;
		s += '<div class="google-rectangle2">'
			+ '<p class="anzeige">Anzeige<\/p>'
			+ '<p class="title"><a href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + unescape(google_ads[i].line1) + '<\/a><\/p>'
			+ '<p><a href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'" class="linkstyle">' + unescape(google_ads[i].line2) + ' ' + unescape(google_ads[i].line3) + '<\/a><\/p>'
			+ '<p><a href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + google_ads[i].visible_url + '<\/a><\/p>'
			+ '<\/div>';

		// FIXME:
		// With postponed loading, the container should be
		// turned to block only *after* receiving content.
		setAttributeForElement('rectangle2', 'display', 'block');
	}
	else if (type == 'skyscraper') {
		var title = google_ads.length == 1 ?
			  'Anzeige'
			: 'Anzeigen';

		s += '<div class="tipps">'
			+ '<div class="tipps-top"><\/div>'
			+ '<div class="tipps-bg">'
			+ '<div class="tipps-inner">'
			+ '<h1 class="tipps-head" style="font-size:11px">' + title + '<\/h1>'
			+ '<div class="webtipps">';

		for (var i = 0; i < google_ads.length; ++i) {
			s += '<h1><a href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + unescape(google_ads[i].line1) + '<\/a><\/h1>'
				+ '<p><a href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + unescape(google_ads[i].line2) + ' ' + unescape(google_ads[i].line3) + '<\/a><\/p>'
				+ '<p><a class="tipplink" href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + google_ads[i].visible_url + '<\/a><\/p>';
		}
		
		s += '<\/div>'
			+ '<\/div>'
			+ '<\/div>'
			+ '<div class="tipps-bottom"><\/div>'
			+ '<\/div>';
	}
	
	document.write(s);
}

// Valid types are fullbanner2-GAL|fullbanner2-VID|fullbanner2-GAME|fullbanner2-CONTENTPOPUP
// Currently type is not needed.
function write_google_ads_popup(google_ads, type) {
	if (!google_ads || google_ads.length == 0) return;

	var s = '<div class="google-popup-fullbanner2">';

	for (var i = 0; i < google_ads.length; ++i) {
		s += '<div class="google-item">'
			+ '<h1><a href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + unescape(google_ads[i].line1) + '<\/a><\/h1>'
			+ '<p><a class="plainstyle" href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + unescape(google_ads[i].line2) + ' ' + unescape(google_ads[i].line3) + '<\/a><\/p>'
			+ '<p><a class="linkstyle" href="' + google_ads[i].url + '" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + google_ads[i].visible_url + '<\/a><\/p>'
			+ '<\/div>';
	}
	
	s += '<div class="google-title">Anzeigen<\/div>'
		+ '<\/div>';
	
	// FIXME:
	// With postponed loading, the container should be
	// turned to block only *after* receiving content.
	setAttributeForElement('fullbanner2', 'display', 'block');

	document.write(s);
}

function write_google_suchergebnisse(google_ads) {
	if (!google_ads || google_ads.length == 0) return;
	
	var s = '<div style="margin:0px 5px 20px 5px;">';

	for (var i = 0; i < google_ads.length; ++i) {
		s += '<div style="padding:12px 0px">'
			+ '<h1><a href="'+ google_ads[i].url +'" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + google_ads[i].line1 + '<\/a><\/h1>'
			+ '<p><a href="'+ google_ads[i].url +'" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">'  + google_ads[i].line2 + ' ' + google_ads[i].line3 + '<\/a><\/p>'
			+ '<p><a class="linkstyle" href="'+ google_ads[i].url +'" target="_blank" onmouseover="window.status=\'' + google_ads[i].visible_url + '\';return true" onmouseout="window.status=\'\'">' + google_ads[i].visible_url + '<\/a><\/p>';
			+ '<\/div>';
	}

	s += '<\/div>';

	document.write(s);
}
