// Adctrl als Singleton
// ganz unten wird eine Instanz auf adctrl erzeugt
// und das taggingInclude inital gesetzt
// @version $Revision: 4818 $

var Adctrl = (function() {
	// Vars
	var instance = undefined;
	
	function PrivateConstructor() {
		// in der PHP Version: Holder für die definierten Klassenkonstanten
		// wird hier durch ein Objekt repräsentiert
		var _classConstants = {
			'AD_BANNER' 	: '468x60',
			'AD_STOPPER' 	: '438x30',
			// const AD_CORNER = '200x300'; gemäß Silke Herrmanns nicht mehr benötigt
			'AD_SKY' 		: '120x600',
			'AD_BUTTON' 	: '120x60', // z.Zt. nur wetter.de
			'AD_POPUP' 		: 'ist',
			'AD_POPUNDER'	: '200x300',
			'AD_RECT_MED'	: '300x250',
			'AD_HALFPAGE'	: '300x250,300x600',
			// const AD_RECT_SMALL = '180x150'; nur bei Element-Girls (externe Agentur)
			'AD_VIDEOAD'	: '320x240',
			'AD_COUNTPIXEL'	: '1x1',
			'ALL_ADS' 		: '__GLOBAL__'
		};
		var _ip_zone = '';
		// Mögliche Werbeformen, die im Taggingtool gesetzt werden
		var _ip_ads = {
			'sky'		: _classConstants['AD_SKY'],
			'banner'	: _classConstants['AD_BANNER'],
			'popunder'	: _classConstants['AD_POPUNDER'],
			'zaehl' 	: _classConstants['AD_COUNTPIXEL']
		};	
		var _ivw = new Array();
		var _offer = 'www.rtl.de';
		// Holder für die Tagging-Variablen aus dem Include
		var _ip_tagging = new Array();
		// Tagging-Include verarbeitet?
		var _ip_tagging_done = 0;
		// Holder für die geparsten Variablen aus dem Tagging
		var _ip_tagging_values = new Array();
		// Tiling or not - this is the question.
		var _ip_tiling = 1;
		// Counter für Tile-Parameter
		var _ip_tile_count = new Array();
		var _taggingIncludePath;
		var _taggingIncludeFile;
		var _taggingInclude;
		// Legt fest, ob das Tagging-Inlclude anhand des ersten IVW-Tags im Baum gesplittet wird.
		var _splitTaggingInclude = 1;
		// Holder für die auszuliefernden Parameter pro AdSlot
		var _adslotParams = new Array();
		// Holder für die bereits ausgelieferten AdSlots
		var _adslotsDelivered = new Array();
		var _countAdslot = new Object();
		_countAdslot['notused1'] 						= 900;
		_countAdslot['notused2'] 						= 0;
		_countAdslot[_classConstants['AD_RECT_MED']] 	= 0;
		_countAdslot[_classConstants['AD_POPUNDER']] 	= 0;
		_countAdslot[_classConstants['AD_POPUP']]	 	= 0;
		_countAdslot[_classConstants['AD_SKY']] 		= 0;
		_countAdslot['notused3'] 						= 0;
		_countAdslot[_classConstants['AD_BANNER']] 		= 0;
		_countAdslot[_classConstants['AD_STOPPER']] 	= 0;
		_countAdslot['notused4'] 						= 0;
		_countAdslot['notused5'] 						= 0;
		_countAdslot['notused6'] 						= 0;
		_countAdslot[_classConstants['AD_BUTTON']]		= 0;
		_countAdslot['notused7'] 						= 0;
		// /Vars

		// Getter für die "Klassenkonstanten"
		this.AD_BANNER = function() {
			return _classConstants['AD_BANNER'];
		};

		this.AD_STOPPER = function() {
			return _classConstants['AD_STOPPER'];
		};

		this.AD_SKY = function() {
			return _classConstants['AD_SKY'];
		};

		this.AD_BUTTON = function() {
			return _classConstants['AD_BUTTON'];
		};

		this.AD_POPUP = function() {
			return _classConstants['AD_POPUP'];
		};

		this.AD_POPUNDER = function() {
			return _classConstants['AD_POPUNDER'];
		};

		this.AD_RECT_MED = function() {
			return _classConstants['AD_RECT_MED'];
		};

		this.AD_HALFPAGE = function() {
			return _classConstants['AD_HALFPAGE'];
		};

		this.AD_VIDEOAD = function() {
			return _classConstants['AD_VIDEOAD'];
		};
		
		this.AD_COUNTPIXEL = function() {
			return _classConstants['AD_COUNTPIXEL'];
		};
				
		// _init() wird am Ende des Konstruktors aufgerufen
		function _init() {
			for (var cnst in _classConstants) {
				_adslotParams[_classConstants[cnst]] = new Array();
			}
			_setDefaults();
		} // /_init
		
		function _setDefaults() {
			_adslotParams['__GLOBAL__'] = {
				'pack'	: window.ip_pack,
				'theme' : window.ip_theme,
				'ord' 	: window.ip_random
			};
			if (typeof(n_pbt)=='string' && n_pbt.length>0)
			{
				_adslotParams['__GLOBAL__'][ 'n_pbt' ] = n_pbt;
			}
			
			// ivw-tag aus window einlesen und parsen
			var ivwWithoutFirstSlash;
			var ivw;
			if(window.ivw.substr(0,1) == '/') {
				ivwWithoutFirstSlash = window.ivw.substr(1);
				ivw = window.ivw;
			} else {
				ivwWithoutFirstSlash = window.ivw;
				ivw = '/' + window.ivw;
			}
			var ivwParts = ivwWithoutFirstSlash.split('/');
			var ivwSubs = new Array();
			var i = 0;
			for (var part in ivwParts) {
				part = ivwParts[part];
				if(i == 0) {
					ivwSubs[i] = part;
				} else {
					ivwSubs[i] = ivwSubs[i-1] + '/' + part;
				}
				i = i + 1;
			}
			_ivw = {
				'full'				: ivw,
				'withoutFirstSlash'	: ivwWithoutFirstSlash,
				'parts'				: ivwParts,
				'subs'				: ivwSubs
			};
		} // /_setDefaults
		
		this.setTaggingInclude = function(path,file) {
			if(path == undefined || path == '') {
				throw('Adctrl.setTaggingInclude: Der Pfad/Dateiname darf nicht leer sein.');
			}
			if(_splitTaggingInclude == 1) {
				_taggingInclude = path;
				return new Boolean(true);
			}
			if(file != undefined && file != '') {
				if(path.substr(path.length-1) != '/') {
					path = path + '/';
				}
				_taggingInclude = path + file;
			} else {
				_taggingInclude = path;
			}
			return new Boolean(true);
		}; // /setTaggingInclude
		
		// Zusätzliche Parameter für einen AdSlot setzen
		// @param $adslot Konstante von RTL_AdControl
		// @param $name Bezeichnung des Parameters
		// @param $value Wert des Parmeters
		// @return void
		function _setAdParam(adslot, name, value) {
			if(_adslotParams[adslot] == undefined) {
				throw('Adctrl._setAdParam: '+adslot+' ist kein bekannter Wert!');
			}
			_adslotParams[adslot][name] = value;
		}

		// überprüft, ob alle benötigten Parameter gesetzt sind.
		function _checkParameters() {
			if(_taggingInclude == undefined || _taggingInclude == '') {
				throw('Das Tagging-Include ist nicht gesetzt. Bitte setzen.');
			}
			if(window.ivw == undefined || window.ivw == '' || window.agof == undefined || window.agof == '') {
				throw('Das IVW-Tag oder der AGOF-Code ist nicht gesetzt. Bitte setzen.');
			}
			return new Boolean(true);
		}
		
		function _getIpTagging() {

			_checkParameters();
			if(_splitTaggingInclude == 1) {
				_taggingInclude = _taggingInclude.replace( /%s/, _ivw['parts'][0] );
			}
			
			if (_ip_tagging_done != 1) {
				ivw_reverse = _ivw['subs'].reverse();
				for(var ad in _ip_ads) {
					if(window[ad] != undefined) {
						// slot-arrays: 
						// banner: 	0 => theme, 1 => pack, 2 => strict, 3 => frei, 4 => dcopt, 5 => freefield
						// sky:		0 => strict, 1 => frei
						// popunder:0 => strict, 1 => frei
						// zaehl:	0 => strict, 1 => frei, 2 => size(1..n)
						// stopper: 0 => frei
						// werden hier auf _ip_tagging[slot-name] geschrieben
						_ip_tagging[ad] = window[ad];
						var firstRun = 1;
						for (var ivw in ivw_reverse) {
							ivw = ivw_reverse[ivw];
							if(_ip_tagging[ad][ivw] != undefined) {
								// im else-Zweig wird strict abgefragt, das je nach slot an versch. Positionen im Array steht
								var strictPos = 0;
								if(ad == 'banner') {
									strictPos = 2;
								} else if(ad == 'stopper') {
									strictPos = 999; // hier gibt es keinen strict-Parameter
								}
								if(firstRun == 1) {
									// komplettes Tag ist im Tagging
									_ip_tagging_values[_ip_ads[ad]] = _ip_tagging[ad][ivw];
									_ip_tagging_values[_ip_ads[ad]]['ivwTagUsed'] = ivw;
									firstRun = 0;
									break;
								}else if(_ip_tagging[ad][ivw][strictPos] != undefined && _ip_tagging[ad][ivw][strictPos] == false) {
									// Vererbung, wenn subtag vererbt werden darf
									_ip_tagging_values[_ip_ads[ad]] = _ip_tagging[ad][ivw];
									_ip_tagging_values[_ip_ads[ad]]['ivwTagUsed'] = ivw;
									firstRun = 0;
									break;
								}
							}
							firstRun = 0;
						}
					}
				}
				if(_ip_tagging_values[_classConstants['AD_BANNER']] != undefined) {
					// slot-arrays: s.o.
					if(_ip_tagging_values[_classConstants['AD_BANNER']][0] != undefined
					&& _ip_tagging_values[_classConstants['AD_BANNER']][0] != '') {
						// Diese Parameter vom Banner gelten für alle AdSlots
						_adslotParams['__GLOBAL__']['theme'] = _ip_tagging_values[_classConstants['AD_BANNER']][0];
						_ip_zone = _ip_tagging_values[_classConstants['AD_BANNER']][0];
					}
					if(_ip_tagging_values[_classConstants['AD_BANNER']][1] != undefined
					&& _ip_tagging_values[_classConstants['AD_BANNER']][1] != '') {
						// Diese Parameter vom Banner gelten für alle AdSlots
						_adslotParams['__GLOBAL__']['pack'] = _ip_tagging_values[_classConstants['AD_BANNER']][1];
					}
					if(_ip_tagging_values[_classConstants['AD_BANNER']][4] != undefined
					&& _ip_tagging_values[_classConstants['AD_BANNER']][4] != '') {
						// Diese Parameter vom Banner gilt nur für den Sky! 
						_setAdParam(_classConstants['AD_SKY'], 'dcopt', 'ist');
					}
					if(_ip_tagging_values[_classConstants['AD_BANNER']][5] != undefined
					&& _ip_tagging_values[_classConstants['AD_BANNER']][5] != '') {
						// Diese Parameter vom Banner gelten für alle AdSlots
						_adslotParams['__GLOBAL__']['free'] = _ip_tagging_values[_classConstants['AD_BANNER']][5];
					}
				}
				if(_ip_tagging_values[_classConstants['AD_COUNTPIXEL']] != undefined) {
					if(_ip_tagging_values[_classConstants['AD_COUNTPIXEL']][3] != undefined
					&& _ip_tagging_values[_classConstants['AD_COUNTPIXEL']][3] != '') {
						var parts = _ip_tagging_values['AD_COUNTPIXEL'][3].split(';');
						if(parts.length > 0) {
							for (var part in parts) {
								part = parts[part];
								if(part == '') {
									continue;
								}
								var subpart = part.split('=');
								if(subpart.length > 1) {
									_setAdParam(_classConstants['AD_COUNTPIXEL'],subpart[0],subpart[1]);
								}
							}
						}
					}
				}
				switch(window.ip_network) {
					case 'www.rtlvip.de':
					case 'rtlvipdsl.de':
						_adslotParams['__GLOBAL__']['u'] = 'www.vip.de' + '-' + _ivw['withoutFirstSlash'];
						break;
					default:
						_adslotParams['__GLOBAL__']['u'] = window.ip_network + '-' + _ivw['withoutFirstSlash'];
						break;
				}				
				_ip_tagging_done = 1;
			}
			
		}
		
		// Erhöht die Zählung für die Adslots
		// @param $adslot
		// @return integer neuer Count-Wert
		function _updateAdslotCount(adslot) {
			if(_countAdslot[adslot] == undefined) {
				return false;
			}
			_countAdslot[adslot] += 1;
			return _countAdslot[adslot];
		}
	
		// das tiling um eins erhöhen
		// @param $adslot
		// @return void
		function _updateTileCount(adslot) {
			if(adslot != undefined && adslot != '') {
				// Warum ein array? Damit man im Debug sehen kann, welcher adslot welchen tile hat!
				_ip_tile_count.push(adslot);
			}
		}
		
		// gibt den code für die Einbindung eines bestimmten AdSlots zurück
		// @param $adslot AdSlot-Größe (Klassenkonstante)
		// @return string
		this.getAd = function(adslot,collector) {
			_getIpTagging();
			var url = 'http://ad.de.doubleclick.net/adj/' + window.ip_network + '/' + _ip_zone + ';';
			var adParamsToDeliver = _adslotParams['__GLOBAL__'];
			var returnStr = '';
			var isLastOfCollectorCalls = false;
			if(adslot == undefined) { // collector: alles muss raus!
				for (var slot in _classConstants) {
					slot = _classConstants[slot];
					if(slot == _classConstants['ALL_ADS']) {
						continue;
					}
					this.getAd(slot, new Boolean('true'));
				}
				isLastOfCollectorCalls = true;
			} else {
				_setAdParam(adslot, 'sz', adslot);
				if(collector && (_ip_tagging_values[adslot] == undefined)) {
					// adslot wird nicht über den collector ausgespielt
					return;
				} 
				if(collector && (_adslotsDelivered[adslot] != undefined)) {
					// adslot kann zwar über den collector raus, wurde aber schon ausgespielt
					return;
				}
			
				_updateAdslotCount(adslot);
				switch(adslot) {
					case _classConstants['AD_BANNER']:
//						var additionalPrefix = '<div id="banner">';
//						var additionalPostfix = '</div>';
						break;
					case _classConstants['AD_SKY']:
						if(typeof(window.ip_closediv) != 'undefined' && window.ip_closediv == 'ja') {
							var additionalPostfix = '</div>';
						}
						break;
					case _classConstants['AD_BUTTON']:
						break;
					case _classConstants['AD_POPUNDER']:
						break;
					case _classConstants['AD_POPUP']:
						break;
					case _classConstants['AD_RECT_MED']:
						break;
					case _classConstants['AD_HALFPAGE']:
						break;
					case _classConstants['AD_STOPPER']:
						adParamsToDeliver['ord'] += '4711';
						break;
					case _classConstants['AD_VIDEOAD']:
						// bitte weitergehen, hier gibt es nichs zu sehen!
						return;
						break;
					case _classConstants['AD_COUNTPIXEL']:
						var additionalPrefix = '<span style="position:absolute;top:0px;left:0px;z-index:3;"><!-- zaehlpixel -->';
						var additionalPostfix = '</span>';
						break;
					default:
						throw('Das Werbemittel '+adslot+' ist nicht bekannt.');
						break;
				}
				
				if(_ip_tiling == 1 && adslot != _classConstants['AD_COUNTPIXEL']) {
					_updateTileCount(adslot);
				}
				
				if( jQuery.inArray(adslot, _ip_tile_count) != -1 ) {
					_setAdParam(adslot, 'tile', _ip_tile_count.length);
				}
				
				//adParamsToDeliver.concat(_adslotParams[adslot]);
				for(adParam in _adslotParams[adslot]) {
					adParamsToDeliver[adParam] = _adslotParams[adslot][adParam];
				}
				
				for(var name in adParamsToDeliver) {
					if(name == 'ord') {
						// ord ist das Letzte!
						continue;
					}
					if (name != 'n_pbt')
					{
						url += name + '=' + adParamsToDeliver[name] + ';';
					}
					else
					{
						url += adParamsToDeliver[name];
					}
				}
				if (typeof AD_VISBILITY_PARAM === 'boolean' && AD_VISBILITY_PARAM === true && typeof adVisibility === 'function')
				{
	           		switch (adslot) {
	           			case _classConstants['AD_BANNER']:
	           			case _classConstants['AD_SKY']:
	           				url += adVisibility($('.isAdVisible').filter(':last'));
	           				break;
	
	           			case _classConstants['AD_HALFPAGE']:
	           				url += ( adVisibility($('.isAdVisible').filter(':last')) + adVisibility($('.halfpageDummy.isAdVisible').filter(':last')).replace('ip_v=', 'ip_v2=') );
	           				break;
	
	           			case _classConstants['AD_RECT_MED']:
	           				url += adVisibility($('.isAdVisible').filter(':last'));
	           				break;
	
	           			default:
		           			break;
	           		}
				}
				url += 'ord=' + adParamsToDeliver['ord'] + '?';

				if(collector) {
					_adslotsDelivered[adslot] = ['collector', adParamsToDeliver];
				} else {
					_adslotsDelivered[adslot] = ['single call', adParamsToDeliver];
				}
				//_updateAdslotCount(adslot);
			}
			
			if (!isLastOfCollectorCalls) {
				var strToPrint = '';
				if (additionalPrefix != undefined) {
					// document.write(additionalPrefix);
					strToPrint = additionalPrefix + strToPrint;
				}
				// document.write('<script type="text/javascript" src="' + url + '"></script>');
				strToPrint = strToPrint + '<script type="text/javascript" src="' + url + '"></script>';
				if (additionalPostfix != undefined) {
					strToPrint = strToPrint + additionalPostfix;
					// document.write(additionalPostfix);
				}
				document.write(strToPrint);
			}
		};
		
   		// Gibt das Zählpixel für die ausgelieferten AdSlots aus
		// @return string IMG-Tag des Zählpixels
		function _getAdslotCount() {
			for(adslot in _adslotsDelivered) {
				_updateAdslotCount(adslot);
			}
			adcount = '';
			for (count in _countAdslot) {
				adcount += _countAdslot[count];
			}
			return '<img src="http://count.rtl.de/'+_offer+'/count.gif?ivw='+_ivw['full']+'&noad='+adcount+'&rnd='+_adslotParams[_classConstants['ALL_ADS']]['ord']+'" width="1" height="1" style="position:absolute;z-index:0;" />';
		}
		
		this.getMultiple = function(adctrl_order) {
			if(adctrl_order == undefined) {
				throw('Adcontrol.getMultiple: keine Parameter übergeben');
			}
			for(doCall in adctrl_order) {
				switch(doCall) {
					case 'singlecall':
						if(typeof adctrl_order[doCall] == 'array') {
							for (var adslot in adctrl_order[doCall]) {
								this.getAd(adctrl_order[doCall][adslot]);
							}
						} else {
							this.getAd(adctrl_order[doCall]);
						}
						break;
					case 'collectorcall':
						this.getAd();
						break;
					case 'adslotcount':
						document.write(_getAdslotCount());
						break;
				}
			}
		};
		
		this.getDebugVarsHtml = function() {
			_getIpTagging();
			var out = '<table border="1"><tr><td colspan="2"><b>DebugVars</b>'+
					'</td></tr><tr><td>geolocation:</td><td>'+_geolocation+
					'</td></tr><tr><td>ivw:</td><td>'+_ivw['full']+
					'</td></tr><tr><td>agof:</td><td>'+_agof+
					'</td></tr><tr><td>tagging_include:</td><td>'+_taggingInclude+
					'</td></tr><tr><td>ip_network:</td><td>'+_ip_network+
					'</td></tr><td>ip_network_schnell:</td><td>'+_ip_network_schnell+
					'</td></tr><td>ip_zone</td><td>'+_ip_zone+
					'</td></tr><tr><td>ip_tagging_values:</td><td>'+_ip_tagging_values+
					'</td></tr><tr><td>adSlots_delivered:</td><td>'+_adslotsDelivered+
					'</td></tr><tr><td>ip_tiling:</td><td>'+_ip_tile_count+
					'</td></tr><tr><td>countAdslots:</td><td>'+_countAdslot;
			for (slot in _adslotParams['__GLOBAL__']) {
				out = out + '</td></tr><tr><td>adslotParam:</td><td>'+slot;
			}
			out = out + '</td></tr></table>';
			return out;
		};
		
		this.getDebugVarsConsole = function() {
			_getIpTagging();
			// console.log('   _location');
			// console.log(window._location);
			// console.log('   ivw');
			// console.log(window.ivw);
			// console.log('   _ivw');
			// console.log(_ivw);
			// console.log('   agof');
			// console.log(window.agof);
			// console.log('   _taggingInclude');
			// console.log(_taggingInclude);
			// console.log('   _ip_network');
			// console.log(window.ip_network);
			// console.log('    _ip_tagging');
			// console.log(_ip_tagging);
			// console.log('   _ip_tagging_values');
			// console.log(_ip_tagging_values);
			// console.log('   _adslotsDelivered');
			// console.log(_adslotsDelivered);
			// console.log('   _ip_tile_count');
			// console.log(_ip_tile_count);
			// console.log('   _countAdslot');
			// console.log(_countAdslot);
			// console.log('   _adslotParams');
			// console.log(_adslotParams);			
		};
		
		_init();
	}
	
    return new function() {
        this.getInstance = function() {
            if (instance == undefined) {
                instance = new PrivateConstructor();
                instance.constructor = undefined;
            }
            return instance;
        };
    };
	
})(); // /Adctrl
adctrl = Adctrl.getInstance();
adctrl.setTaggingInclude('http://www.rtl.de/includes/adctrl_%s.js');

