function idn_convert($domain) {
	if(strpos($domain, 'xn--') !== false) {
		$slash = strpos($domain, '/');
		if($slash == 5) {
			$domain = 'http://'.utf8_decode(idn_to_utf8(substr($domain, 7)));
		} elseif($slash == 6) {
			$domain = 'https://'.utf8_decode(idn_to_utf8(substr($domain, 8)));
		}
	}
	return $domain;
}
$id = empty($_GET['id']) ? '' : (int)$_GET['id'];
$blockedCounters = array(41930, 40504, 42263, 39594, 41454, 43764, 54364, 54891, 43697);
if(in_array($id, $blockedCounters)) {
	die();
}
// don't allow livecounter on localhost
if(strstr($_SERVER['HTTP_REFERER'], 'http://localhost') OR strstr($_SERVER['HTTP_REFERER'], 'http://127.0.0.1')) {
	die();
}
header('Content-type: application/javascript');
$ip = $_SERVER['REMOTE_ADDR'];
if($ip != '178.63.96.77') {
	include_once('includes/sql.php');
	$img = !isset($_GET['img']) ? '1' : $_GET['img'];
	$text = 'document.write(\'Få en gratis bes?gst?ller med live statistik til din hjemmeside på LiveCounter.dk\');';
	if(!empty($id)) {
		$httpreferer = empty($_SERVER['HTTP_REFERER']) ? '' : idn_convert(strtolower($_SERVER['HTTP_REFERER']));
		$counterquery = mysql_query("SELECT site, affiliateTracking, createdBy FROM counters WHERE id = '$id' LIMIT 1") or die(mysql_error());
		if(mysql_num_rows($counterquery) != 0) {
			$counterrow = mysql_fetch_assoc($counterquery);
			if(empty($counterrow['site']) && !empty($httpreferer) && preg_match("/https?:\/\/(.*?)\//i", $httpreferer, $page)) {
				$page2 = str_replace('www.', '', $page[1]);
				$query = mysql_query("SELECT id FROM counters WHERE site = '$page[1]' OR site = 'www.$page[1]' OR site = '$page2' LIMIT 1") or die(mysql_error());
				if(mysql_num_rows($query) == 0) {
					$http = $httpreferer[4] == 's' ? 1 : 0;					
					mysql_query("UPDATE counters SET site = '$page[1]', secure = '$http', userid = '$counterrow[createdBy]' WHERE id = '$id' LIMIT 1") or die(mysql_error());
				} else {
					die('document.write(\'Der findes allerede en bes?gst?ller for dette domæne! Læs mere på vores hjælpe og informationsside\');');
				}
			}
			$counterdomain = empty($page[1]) ? $counterrow['site'] : $page[1];
			if(preg_match("/https?:\/\/(.*?)\//i", $httpreferer, $domain)) {
				if($counterdomain == $domain[1] || 'www.'.$counterdomain == $domain[1] || $counterdomain == 'www.'.$domain[1]) {
					if($counterrow['affiliateTracking'] == 1) {
						// se om der findes et affilaite visit
						$uuid = md5($ip.$id.$_SERVER['HTTP_USER_AGENT']);
						$findVisit = mysql_query("SELECT visits_id FROM affiliate_visits WHERE visits_epi = '$uuid' AND used = 0 LIMIT 1");
						if(mysql_num_rows($findVisit) == 0) {
							$now = time();
							mysql_query("INSERT INTO affiliate_visits (visits_epi, visits_timestamp, counters_id, visits_ip, http_user_agant) VALUES ('$uuid', '$now', '$id', '$ip', '".$_SERVER['HTTP_USER_AGENT']."')") or die(mysql_error());
						} 
						?>
(function(){
    var DomReady = window.DomReady = {};
	// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 
    var userAgent = navigator.userAgent.toLowerCase();
    // Figure out what browser is being used
    var browser = {
    	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    	safari: /webkit/.test(userAgent),
    	opera: /opera/.test(userAgent),
    	msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
    	mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };    
	var readyBound = false;	
	var isReady = false;
	var readyList = [];
	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if(!isReady) {
			// Remember that the DOM is ready
			isReady = true;
        
	        if(readyList) {
	            for(var fn = 0; fn < readyList.length; fn++) {
	                readyList[fn].call(window, []);
	            }
            
	            readyList = [];
	        }
		}
	};
	// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      if (oldonload) {
	        oldonload();
	      }
	      func();
	    }
	  }
	};
	// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
	function bindReady() {
		if(readyBound) {
		    return;
	    }
	
		readyBound = true;
		// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
		if (document.addEventListener && !browser.opera) {
			// Use the handy event callback
			document.addEventListener("DOMContentLoaded", domReady, false);
		}
		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if (browser.msie && window == top) (function(){
			if (isReady) return;
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
		    domReady();
		})();
		if(browser.opera) {
			document.addEventListener( "DOMContentLoaded", function () {
				if (isReady) return;
				for (var i = 0; i < document.styleSheets.length; i++)
					if (document.styleSheets[i].disabled) {
						setTimeout( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
	            domReady();
			}, false);
		}
		if(browser.safari) {
		    var numStyles;
			(function(){
				if (isReady) return;
				if (document.readyState != "loaded" && document.readyState != "complete") {
					setTimeout( arguments.callee, 0 );
					return;
				}
				if (numStyles === undefined) {
	                var links = document.getElementsByTagName("link");
	                for (var i=0; i < links.length; i++) {
	                	if(links[i].getAttribute('rel') == 'stylesheet') {
	                	    numStyles++;
	                	}
	                }
	                var styles = document.getElementsByTagName("style");
	                numStyles += styles.length;
				}
				if (document.styleSheets.length != numStyles) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			
				// and execute any waiting functions
				domReady();
			})();
		}
		// A fallback to window.onload, that will always work
	    addLoadEvent(domReady);
	};
	// This is the public function that people can use to hook up ready.
	DomReady.ready = function(fn, args) {
		// Attach the listeners
		bindReady();
    
		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call(window, []);
	    } else {
			// Add the function to the wait list
	        readyList.push( function() { return fn.call(window, []); } );
	    }
	};
    
	bindReady();
	
})();
DomReady.ready(function() {
	for(i = 0; i < document.links.length; i++) {
		lclink = document.links[i];
		if(lclink.href.indexOf('partner-ads.com') != -1 && (lclink.href.indexOf('&uid2=') == -1 && lclink.href.indexOf('?uid2=') == -1)) {
			lclink.href = lclink.href.replace('klikbanner.php?', 'klikbanner.php?uid2=lc_&');
		} else if(lclink.href.indexOf('pdt.tradedoubler.com') != -1 && lclink.href.indexOf('\)epi2\(') == -1) {
			lclink.href = lclink.href + 'epi2(lc_)';
		} else if(lclink.href.indexOf('clk.tradedoubler.com') != -1) {
			if(lclink.href.indexOf('p\(') != -1) {
				if(lclink.href.indexOf('\)epi2\(') == -1) {
					lclink.href = lclink.href + 'epi2(lc_)';
				}
			} else {
				if(lclink.href.indexOf('&epi2=') == -1 && lclink.href.indexOf('?epi2=') == -1) {
					lclink.href = lclink.href.replace('click?', 'click?epi2=lc_&');
				}
			}
		} else {
			lclink.href = lclink.href.replace('LC_EPI', 'lc_');
		}
	}
});
						
					}
					$http = $httpreferer[4] == 's' ? 'https' : 'http';
					if($img == '0') {
						echo 'document.write(\' + \') \');';
					} else {
						echo 'document.write(\'
\');';
					} else {
						echo 'document.write(\' + \') \');';
					}
				} else {
					echo $text;
				}
			} else {
				echo $text;
			}
		} else {
			echo $text;
		}
	}
}
?>
\');';
					}
				} else {
					echo $text;
				}
			} else {
				echo $text;
			}
		} else {
			echo $text;
		}
	}
}
?>