if (!window.console) {
	var names = [ "log", "debug", "info", "warn", "error", "time", "timeEnd" ];
	window.console = {};
	for (n in names) {
		window.console[names[n]] = function() {
		};
	}
}
if (true) {
	console.warn("Twyn JSONP - Server for testNetzwerk - NO Rules found");
} else {
	console.info("Twyn JSONP - Server for testNetzwerk");

	twyn_as.trackingServer = "tracknet.twyn.com";

	twyn_as.setCookies = function(json) {
		twyn_as.cookies = json;
		console.debug("setCookies", twyn_as.cookies);
		twyn_as.render();
	};

	//Find Bee Cookie
	twyn_as.getCV = function(name) {
		var val = twyn_as.cookies[name.replace(/\s+/, '')];
		if (val !== undefined) {
			console.debug("Found Cookie ", name, val);
		} else {
			console.info("Did'nt find Cookie ", name);
		}
		return val;
	};
	//Return Clicks of viewCookie
	twyn_as.getC = function(cookieValue) {
		var cvPart = cookieValue.split('.');
		if (cvPart.length > 1 && cvPart[1].length > 2) {
			return parseInt(cvPart[1].substring(2, 3), 36);
		}
		return 0;
	};
	//Return Clicks of viewCookie
	twyn_as.getV = function(cookieValue) {
		var cvPart = cookieValue.split('.');
		if (cvPart.length > 1 && cvPart[1].length > 1) {
			return parseInt(cvPart[1].substring(1, 2), 36);
		}
		return 0;
	};
	//Return Counter of viewCookie 
	twyn_as.getCN = function(cookieValue) {
		var cvPart = cookieValue.split('.');
		if (cvPart.length > 1 && cvPart[1].length > 3) {
			return parseInt(cvPart[1].substring(3, 4), 36);
		}
		return 0;
	};
	//Return Age of viewCookie 
	twyn_as.getAge = function(cookieValue) {
		var cvPart = cookieValue.split('.');
		if (cvPart.length > 2 && cvPart[2].length >= 4) {
			// minuten seit dem 1.1.2009, 0h
			console.debug("Created: %d, Minutes: %d",cvPart[2], parseInt(cvPart[2].substring(0, 4), 36));
			var then = 1230764400000+parseInt(cvPart[2].substring(0, 4), 36)*60*1000;		
			// -> millisekunden seit 1.1.1970
			console.info("Cookie Created: %d days ago",Math.floor((new Date().getTime()-then)/1000/60/60/24));
			return Math.floor((new Date().getTime()-then)/1000/60/60/24); 
			// unterschied in tagen
		}
		return 0;
	};
	//Return Modified-Age of viewCookie 
	twyn_as.getModified = function(cookieValue) {
		var cvPart = cookieValue.split('.');
		if (cvPart.length > 2 && cvPart[2].length >= 8) {
			// minuten seit dem 1.1.2009, 0h
			console.debug("Modified: %d, Minutes: %d",cvPart[2], parseInt(cvPart[2].substring(4, 8), 36));
			var then = 1230764400000+parseInt(cvPart[2].substring(4, 8), 36)*60*1000;		
			// -> millisekunden seit 1.1.1970
			console.info("Cookie Modified: %d days ago",Math.floor((new Date().getTime()-then)/1000/60/60/24));
			return Math.floor((new Date().getTime()-then)/1000/60/60/24); 
			// unterschied in tagen
		} 	
		return twyn_as.getAge(cookieValue);
	};

	//Parse Bee Cookie & Return Person with Interests, Hashes,..
	twyn_as.parseBeeCookie = function(value) {
		var ivisit = {
			'rendered' : false
		};

		// interest.interest|demographic|hashhashhashhash|version
		var parts = value.split("|");
		
		// version
		ivisit.version = parseInt(parts[parts.length-1]);
		
		console.info("Beecookie Version ",ivisit.version);
		
		// interessen
		var ints = parts[0].split(".");
		ivisit.ints = {};
		ivisit.list = [];
		for ( var i in ints) {
			var l = ints[i].length;
			if (l > 3) {
				var intr = {};
				if (ivisit.version==4) {				
					intr.i = ints[i].substring(0, l - 4);
					intr.v = parseInt(ints[i].substring(l - 4, l - 3), 36);
					intr.c = parseInt(ints[i].substring(l - 3, l - 2), 36);
					intr.m = parseInt(ints[i].substring(l - 2, l - 1), 36);
					intr.d = parseInt(ints[i].substring(l - 1), 36);				
				} else {
					intr.i = ints[i].substring(0, l - 3);
					intr.v = parseInt(ints[i].substring(l - 3, l - 2), 36);
					intr.c = parseInt(ints[i].substring(l - 2, l - 1), 36);
					intr.m = parseInt(ints[i].substring(l - 1), 36);
				}
				console.debug("%o",intr);
				ivisit.ints[intr.i] = intr;
				ivisit.list.push(intr.i);
			}
		}

		ivisit.hashes = {};
		var hashes = parts[2];
		while (hashes.length >= 8) {
			var hash = {};
			// hash
			hash.h = hashes.substring(0, 5);
			// view
			hash.v = parseInt(hashes.charAt(5), 36);
			// click
			hash.c = parseInt(hashes.charAt(6), 36);
			// month
			hash.m = parseInt(hashes.charAt(8), 36);
			ivisit.hashes[hash.h] = hash;
			hashes = hashes.substring(9);
			ivisit.list.push(hash.h);
		}

		/**
		 * Render the Ad specified through AdId
		 */
		ivisit.showAd = function(jsid, advidb36, caidb36, cd, page, loc, hit, ruleno, width, height, url, geoC, c, v, list) {
			console.debug("showAd %s %s %s %s", jsid, advidb36, caidb36, url, list);
			// function(jsid, advid, caid, cd, page,loc)

			var rot13 = function(from) {
				return from.replace(/[a-zA-Z]/g, function(c) {
					return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
				});
			};

			var cInfo = "";

			cInfo += "&campC=" + c + "&campC=" + v;

			if (list !== undefined) {
				cInfo += "&visitList=" + list;
			}

			var advid = parseInt(advidb36, 36);

			var link = "http://herodot.twyn.com/filestore/herodot/bannerpool/" + advid + "/" + cd[0];

			var curl = "http://" + twyn_as.trackingServer + "/c?cuid=" + advidb36 + "&caid=" + caidb36 + "&cr=" + hit +
					"&cd=" + cd[0] + "&dp=" + page + "&ac=" + loc + "&pa=bee&pd=bee&ox4=" + hit + "&redirect=" + url;
			var vurl = "http://" + twyn_as.trackingServer + "/v?cuid=" + advidb36 + "&caid=" + caidb36 + "&cr=" + hit +
					"&cd=" + cd[0] + "&dp=" + page + "&ac=" + loc + "&pa=bee&pd=bee&ox4=" + hit;

			if (cd[0].match(".swf")) {
				// clicktag
				document.write("<object width='" + width + "' height='" + height + "'><param name='movie' value='" + link +
						"'/><param name='FlashVars' value='clicktag=" + escape(curl) + cInfo + "'/><embed src='" + link +
						"' width='" + width + "' height='" + height + "' FlashVars='clicktag=" + escape(curl) + cInfo +
						"'></embed></object>");
			} else {
				// link click
				document.write('<a href="' + curl + '" target="_blank"><img src="' + link + '" style="border: none;"/></a>');
			}
			// view
			document.write('<img src="' + vurl + '" width="1" height="1" border="0"/>');
		};
		return ivisit;
	};

	twyn_as.render = function() {

		// bee cookie auslesen, parsen (-> interessen, ->op4s, clicks, views)
		var beeCookie = twyn_as.getCV('bee');

		var page = 'testNetzwerk';
		var loc = twyn_as.params['l'];

		if (beeCookie) {
			var visit = twyn_as.parseBeeCookie(beeCookie);
			// fuer jede bee kampagen pruefen, ob angezeigt

			var rules = [];

			var hit = ""; // was hat gezogen

			//Does the visit have a doping
			d = function(pos,co) {
				// co: coolingOff
				if (visit.hashes[pos] !== undefined) {
					hit = pos;
					console.debug("doping %s!", pos);
					return true;
				}
				console.debug("NO doping %s", pos);
				return false;
			};

			//Does the visit have an interest
			i = function(pos,co) {
				if (visit.ints[pos] !== undefined) {
					hit = pos;
					console.debug("interest %s!", pos);
					return true;
				}
				console.debug("NO interest %s", pos);
				return false;
			};

			var width = twyn_as.params['w'];
			var height = twyn_as.params['h'];

			for ( var r in rules) {
				if (rules[r].length == 6 && visit.rendered === false) {
					var str = rules[r][1];
					var cv = twyn_as.getCV('c' + rules[r][0]); // cookievalue(c + jsId)
					var c = 0;
					var v = 0;
					var lt = 0; // cookie age (lifetime)
					var cn = function(period) {
						return 0;
					};
					
					if (cv !== undefined) {
						// cookie gefunden
						c = twyn_as.getC(cv);
						v = twyn_as.getV(cv);
						lt = twyn_as.getAge(cv);
						
						// cn: contakte im aktuellen interval
						var cn = function(period) {
							var counter = twyn_as.getCN(cv);
							var m_age = twyn_as.getModified(cv);
							if (m_age>period) {
								console.debug("Cookie is old enough");
								return 0; // letzter contact ausreichend lange her 
							}
							if (Math.floor(lt/period)>Math.floor((lt-m_age)/period)) {
								console.debug("New interval");
								return 0; // neues interval
							}
							console.debug("%i contacts in current interval",counter);
							return counter;
						};
						
					} else {
					// sonst: 0 clicks, 0 views
					  console.info("No Cookie found for Campaign %s",rules[r][0]);
					} 
					try {
						if (eval(str)) {
							var format = rules[r][4].match(hit + "_" + width + "x" + height + "\.[a-z]{3}");
							if (format === null) {
								// fallback
								console.info("Did not find format %s", hit + "_" + width + "x" + height + ".xxx");
								format = rules[r][4].match(width + "x" + height + "\.[a-z]{3}");
							}
							if (format !== null) {
								console.info("Found format %s", format[0]);
								console.info("Rule %s is true (v:%i,c:%i): Rendering '%s' for '%i'", str, v, c, rules[r][0], hit);
								// ["r8 ","c<1 && v<10 && d('8z7ra')","5","82cq"]
								// jsid, rule, advid, caid, formats
								// showAd = function(jsid, advid, caid, cd, page, loc, hit, ruleno)
								visit.showAd(rules[r][0], rules[r][2], rules[r][3], format, page, loc, hit, r, width, height,
										rules[r][5], twyn_as.getCV('geo'), c, v, visit.list);
								visit.rendered = true;
								twyn_as.rendered = true;
							} else {
								console.warn("Requested Size %ix%i not found", width, height);
							}
						} else {
							console.info("Rule %s is wrong (v:%i,c:%i): Not rendering '%s'", str, v, c, rules[r][0]);
						}
					} catch (e) {
						console.warn("Rule %s Error: %o", str, e);
					}
				} else {
					console.info("Rule %i: Already rendered something else",r);
				}
			}
		}
		if (visit === undefined || visit.rendered === undefined || visit.rendered === false) {
			// nichts gefunden
			if (twyn_as.alternative !== undefined && twyn_as.alternative !== null && twyn_as.alternative !== "") {
				console.info("Nothing found, Rendering ", twyn_as.alternative);
				document.write("<script type='text/javascript' src='" + twyn_as.alternative + "'></script>");
				twyn_as.rendered = true;
			} else {
				console.info("Nothing found, Back to Page");
			}
		}
	};

	if (document.cookie) {
		var script = document.createElement('script');
		// Tracknet Cookie Servlet
		script.setAttribute('src', 'http://' + twyn_as.trackingServer + '/cs?p=' + escape('testNetzwerk') + '&l=' +
				escape(twyn_as.params['l']));
		document.getElementsByTagName('head')[0].appendChild(script);
	} else {
		console.info("No Cookies found at all");
	}
}
