Tagging = function(context) {
  this.site = 'playboy-nl-pla';
  this.zone = 'articles';
  this.source_consent_cookie = 'site_consent';
  this.source_default_tracking = true;
  this.protocol = window.location.protocol;
  this.autodetect_url = this.protocol + '//cts.snmmd.nl/service/detect/';
  this.context = context;
  this.positions = {};
  this.positions_weighted = {};

  this.positions['footer'] = '[{\"service_name\": \"STIR\", \"source_non_tracking\": \"\", \"weight\": null, \"service_kind\": \"stir\", \"source_tracking\": \"<script language=\'JavaScript1.1\' type=\'text/javascript\'>(\'smm\'.length != 0) ? stir_customer = \'smm\' : stir_customer = \'sanoma\'; (\'teller\'.length != 0) ? stir_counter = \'teller\' : stir_counter = \'stir\';(\'entertainment\'.length != 0) ? stir_channel = \'&amp;ns_channel=entertainment\' : stir_channel = \'\';(\'${stir_webdir}\'.length != 0) ? stir_webdir = \'&amp;ns_webdir=${stir_webdir}\' : stir_webdir = \'\'; (\'\'.length != 0) ? stir_context = \'&amp;ns_context=\' : stir_context = \'\'; (\'${stir_auto}\'.length != 0) ? stir_auto = \'&amp;ns_auto=${stir_auto}\' : stir_auto = \'\';(\'smm-geslaagde_mannen,smm-Digitaal_Lifestyle\'.length != 0) ? stir_stir4 = \'&amp;ns_stir4=smm-geslaagde_mannen,smm-Digitaal_Lifestyle\' : stir_stir4 = \'\';function sitestat(ns_l){ns_l+=\'&amp;ns__t=\'+(new Date()).getTime();ns_pixelUrl=ns_l;ns_0=document.referrer;ns_0=(ns_0.lastIndexOf(\'/\')==ns_0.length-1)?ns_0.substring(ns_0.lastIndexOf(\'/\'),0):ns_0;if(ns_0.length>0)ns_l+=\'&amp;ns_referrer=\'+escape(ns_0);if(document.images){ns_1=new Image();ns_1.src=ns_l;}elsedocument.write(\'<img src=\\"\'+ns_l+\'\\" width=\\"1\\" height=\\"1\\" alt=\\"\\">\');}if(document.cookie.indexOf(\'ns_Cfilter\')!=-1)sitestat(\\"http://nl.sitestat.com/\\"+stir_customer+\\"/playboy/s?\\"+stir_counter+stir_channel+stir_webdir+stir_context+stir_auto+stir_stir4);</script>\"}, {\"service_name\": \"STIR\", \"source_non_tracking\": \"\", \"weight\": null, \"service_kind\": \"stir\", \"source_tracking\": \"<!-- Begin comScore Inline Tag 1.1105.27 --><script type=\\"text/javascript\\"> /* <![CDATA[ */cts_stir = \'c1=2\'; cts_stir += \'&c2=6035634\';cts_stir += \'&c4=\'+window.location.href;cts_stir_webdir = (\'${stir_webdir}\'.length > 0) ? \'&c5=${stir_webdir}\' : \'\';cts_stir_segment = \'\';cts_stir_segment = (\'\'.length > 0) ? \'&c6=\'+escape(\'\') : cts_stir_segment;cts_stir_segment = (\'${stir_segment_zone}\'.length > 0) ? \'&c6=\'+escape(\'${stir_segment_zone}\') : cts_stir_segment;function comScore(t){var b=\\"comScore\\",o=document,f=o.location,a=\\"\\",e=\\"undefined\\",g=2048,s,k,p,h,r=\\"characterSet\\",n=\\"defaultCharset\\",m=(typeof encodeURIComponent!=e?encodeURIComponent:escape);if(o.cookie.indexOf(b+\\"=\\")!=-1){p=o.cookie.split(\\";\\");for(h=0,f=p.length;h<f;h++){var q=p[h].indexOf(b+\\"=\\");if(q!=-1){a=\\"&\\"+unescape(p[h].substring(q+b.length+1))}}}t=t+\\"&ns__t=\\"+(new Date().getTime());t=t+\\"&ns_c=\\"+(o[r]?o[r]:(o[n]?o[n]:\\"\\"))+\\"&c8=\\"+m(o.title)+a+\\"&c7=\\"+m(f&&f.href?f.href:o.URL)+\\"&c9=\\"+m(o.referrer);if(t.length>g&&t.indexOf(\\"&\\")>0){s=t.substr(0,g-8).lastIndexOf(\\"&\\");t=(t.substring(0,s)+\\"&ns_cut=\\"+m(t.substring(s+1))).substr(0,g)}if(o.images){k=new Image();if(typeof ns_p==e){ns_p=k}k.src=t}else{o.write([\\"<\\",\\"p\\",\\"><\\",\'img src=\\"\',t,\'\\" height=\\"1\\" width=\\"1\\" alt=\\"*\\"\',\\"><\\",\\"/p\\",\\">\\"].join(\\"\\"))}};comScore(\'http\'+(document.location.href.charAt(4)==\'s\'?\'s://sb\':\'://b\')+\'.scorecardresearch.com/p?\'+cts_stir+cts_stir_webdir+cts_stir_segment);/* ]]> */</script><!-- End comScore Inline Tag -->\"}]';
  this.positions_weighted['footer'] = false;
  
  this.positions['head'] = '[{\"service_name\": \"Sanoma cookie opt-in\", \"source_non_tracking\": \"<script type=\\"text/javascript\\">    (function() {        function get_domain() {            var host = window.location.host;            var port = host.indexOf(\':\');            var domain = port>0?host.substr(0,port):host;            var parts = domain.split(\'.\');            return parts[parts.length-2]+\'.\'+parts[parts.length-1];        }        var url = window.location.protocol+\'//privacy.\'+get_domain()+\'/script/consent.js\';        var script = \'<scr\'+\'ipt type=\\"text/javascript\\" src=\\"\'+url+\'\\"></scr\'+\'ipt>\';        document.write(script);    })();</script>\", \"weight\": null, \"service_kind\": \"functional\", \"source_tracking\": \"<script type=\\"text/javascript\\">    (function() {        function get_domain() {            var host = window.location.host;            var port = host.indexOf(\':\');            var domain = port>0?host.substr(0,port):host;            var parts = domain.split(\'.\');            return parts[parts.length-2]+\'.\'+parts[parts.length-1];        }        var url = window.location.protocol+\'//privacy.\'+get_domain()+\'/script/consent.js\';        var script = \'<scr\'+\'ipt type=\\"text/javascript\\" src=\\"\'+url+\'\\"></scr\'+\'ipt>\';        document.write(script);    })();</script>\"}, {\"service_name\": \"Wunderloop\", \"source_non_tracking\": \"<script type=\\"text/javascript\\">var wlrcmd=\'\';function KruxDummy () {  this.user = \'\';  this.segments = \'\';}var Krux = new KruxDummy();</script>\", \"weight\": null, \"service_kind\": \"interests\", \"source_tracking\": \"<script type=\\"text/javascript\\">  var WlWebsiteId=\\"playboy.nl\\";if(typeof(wlrcmd)==\\"undefined\\"){var wlrcmd=\\"\\";}  if (\\"${wl_contentgroup}\\".length != 0) {var WlContentGroup = \\"${wl_contentgroup}\\";}  if (\\"${contentgroup}\\".length != 0) {var WlContentGroup = \\"${contentgroup}\\";}  var WlBase=location.protocol.indexOf(\'https\')>-1?\'https://cts.snmmd.nl\':\'http://cts.snmmd.nl\';  document.write(\'<scr\'+\'ipt src=\\"\'+WlBase+\'/lib/js/gt.js\\"></scr\'+\'ipt>\');  if (\\"${search}\\".length != 0) {    var wl_ord = new Date().getTime();    var WlSearch = \\"${search}\\";     document.write(\'<img src=\\"\' + \'http://tr.bt.ilsemedia.nl/Cnt/ilsemedia/CP/Search?Keywords=\' + WlSearch + \'&d=\' + wl_ord + \'\\" width=\\"0\\" height=\\"0\\" border=\\"0\\" style=\\"display: none;\\">\');  }     </script><style>a.adch{position:absolute;z-index:99;width:20px;height:15px;margin-left:-20px;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE0AAAAPCAMAAACWR7LlAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGBQTFRFR0dHNjY219rbAqzKJrTNFbHMesbUQrvPSLvQxdfaU77Rk8zVZMLSh8nVBa7KCa7LutTZbsPTOrnOzNjanc7WXsDSbm5upKSktra2e3t7zc3NYWFh+/v7AAAA29vb////LceoagAAACB0Uk5T/////////////////////////////////////////wBcXBvtAAAAs0lEQVR42qzTyQ6EIAwAUFZxRdxwmaH8/1+qYbjhyKFNSi/NS5oWAphBQlGiY3haz7WY0TQ+mJIrk+5ZaWx2Nk8rgDWCL9VfzR2Qqw0LFL0sWFKjH0ePKzd6ZY42NwCT4mNSczuQfXMrsWBJjlYrgEpxldYArL1ed8+bpZVTq2XHkDQp9TA9bCFqb5P6oLWm1XX1eCFRe9uC/11vbwzC9frvXUbRoPxTHzikX+/vwNJOAQYAW9F9daXna+0AAAAASUVORK5CYII=);background-repeat:no-repeat;left:100%;}\t\ta.adch2s{width:77px;margin-left:-77px;}\t\ta.adch:visited{width:20px;}                a.adch:hover{width:77px;margin-left:-77px;}  .adchclearfix:after {    content: \\".\\";    display: block;    height: 0;    clear: both;    visibility: hidden;    }.adchclearfix {display: inline-block;} </style><script type=\\"text/javascript\\">if (navigator.userAgent.indexOf(\\"IE\\") != -1) {  document.write(\\"<st\\"+\\"yle>.adchclearfix{ display:block; }</st\\"+\\"yle>\\");}</script>\"}, {\"service_name\": \"Krux Digital\", \"source_non_tracking\": \"<script type=\\"text/javascript\\">var wlrcmd=\'\';var Krux = function () {};Krux.user = \'\';Krux.segments = \'\';</script>\", \"weight\": null, \"service_kind\": \"interests\", \"source_tracking\": \"<script class=\\"kxct\\" data-id=\\"Hhv9mPEw\\" data-version=\\"sync:1.7\\" type=\\"text/javascript\\"> (function(){ var m,src=(m=location.href.match(/\\\\bkxsrc=([^&]+)/))&&decodeURIComponent(m[1]); src = /^https?:\\\\/\\\\/([^\\\\/]+\\\\.)?krxd\\\\.net(:\\\\d{1,5})?\\\\//i.test(src) ? src : src === \\"disable\\" ? \\"\\" : (location.protocol===\\"https:\\"?\\"https:\\":\\"http:\\")+\\"//cdn.krxd.net/controltag?confid=Hhv9mPEw\\"; document.write(\\"<scr\\"+\\"ipt type=\\\\\\"text/javascript\\\\\\" src=\\\\\\"\\"+src+\\"\\\\\\"></scr\\"+\\"ipt>\\"); })();</script>\"}, {\"service_name\": \"Doubleclick\", \"source_non_tracking\": \"\", \"weight\": null, \"service_kind\": \"ads\", \"source_tracking\": \"<script type=\'text/javascript\'>var googletag = googletag || {};googletag.cmd = googletag.cmd || [];(function() {var gads = document.createElement(\'script\');gads.async = true;gads.type = \'text/javascript\';var useSSL = \'https:\' == document.location.protocol;gads.src = (useSSL ? \'https:\' : \'http:\') + \'//www.googletagservices.com/tag/js/gpt.js\';var node = document.getElementsByTagName(\'script\')[0];node.parentNode.insertBefore(gads, node);})();function strToGPT(s){var h={};s=s.split(\\";\\");for(var i=0;i<s.length;i++){var p=s[i].split(\\"=\\",2),k=p[0],v=\\"\\";if(p.length==2)v=p[1];var m=v.split(\',\');for(var u=0;u<m.length;u++){if(k&&m[u])(typeof h[k]==\\"undefined\\")?h[k]=[m[u]]:h[k].push(m[u])}}return h}var _VMp = (Math.floor(Math.random()*100000000));function GPTrid() {if(typeof window.GPTrcmd==\\"undefined\\") {if (\'${dc_keywords}\'.length == 0) { kw=wlrcmd; } else { kw=\'${dc_keywords},\'+wlrcmd;}if (\'${dc_params}\'.length == 0) { params=\'\'; } else { params=\';${dc_params}\';}if(window.enr_initScan) { kw += \';VM=true\' }window.GPTrcmd = strToGPT(params+\';kw=\'+kw);}var _VMa = (Math.floor(Math.random()*100000000));return \'VMspot_\'+window._VMp+\'_\'+_VMa;}</script>\"}]';
  this.positions_weighted['head'] = false;
  
  this.positions['multiple-rectangle'] = '[{\"service_name\": \"Doubleclick\", \"source_non_tracking\": \"<script type=\\"text/javascript\\">document.write(\'<scr\'+\'ipt type=\\"text/javascript\\" src=\\"http://ad.360yield.com/adj?p=2801&w=336&h=280&tz=\'+(new Date().getTimezoneOffset())+\'&click3rd=&optin=n\\"><\\/scr\'+\'ipt>\');</script>\", \"weight\": 1, \"service_kind\": \"ads\", \"source_tracking\": \"<script type=\\"text/javascript\\">var uid = GPTrid();document.write(\'<div id=\\"\'+uid+\'\\"></div>\');var GPTtag = \\"googletag.cmd.push(function(){googletag.defineSlot(\'/4442/P4442.Playboy/articles\', [[300, 250], [336, 280]], \'\\"+uid+\\"\').addService(googletag.pubads())\\";if(typeof GPTrcmd == \'object\'){for (var k in GPTrcmd) {GPTtag += \\".setTargeting(\'\\"+k+\\"\', \'\\"+GPTrcmd[k]+\\"\')\\";}}GPTtag += \\".setTargeting(\'VMspot\', \'\\"+uid.replace(\'VMspot_\',\'\')+\\"\')\\";GPTtag += \\";googletag.enableServices();googletag.display(\'\\"+uid+\\"\');});\\";eval(GPTtag);if(window.enr_initScan) { window.enr_initScan(uid); }</script>\"}]';
  this.positions_weighted['multiple-rectangle'] = true;
  
  this.positions['multiple-top'] = '[{\"service_name\": \"Doubleclick\", \"source_non_tracking\": \"<script type=\\"text/javascript\\">document.write(\'<scr\'+\'ipt type=\\"text/javascript\\" src=\\"http://ad.360yield.com/adj?p=2802&w=728&h=90&tz=\'+(new Date().getTimezoneOffset())+\'&click3rd=&optin=n\\"><\\/scr\'+\'ipt>\');</script>\", \"weight\": 1, \"service_kind\": \"ads\", \"source_tracking\": \"<script type=\\"text/javascript\\">var uid = GPTrid();document.write(\'<div id=\\"\'+uid+\'\\"></div>\');var GPTtag = \\"googletag.cmd.push(function(){googletag.defineSlot(\'/4442/P4442.Playboy/articles\', [[468, 60], [728, 90]], \'\\"+uid+\\"\').addService(googletag.pubads())\\";if(typeof GPTrcmd == \'object\'){for (var k in GPTrcmd) {GPTtag += \\".setTargeting(\'\\"+k+\\"\', \'\\"+GPTrcmd[k]+\\"\')\\";}}GPTtag += \\".setTargeting(\'VMspot\', \'\\"+uid.replace(\'VMspot_\',\'\')+\\"\')\\";GPTtag += \\";googletag.enableServices();googletag.display(\'\\"+uid+\\"\');});\\";eval(GPTtag);if(window.enr_initScan) { window.enr_initScan(uid); }</script>\"}]';
  this.positions_weighted['multiple-top'] = true;
  
  this.positions['skyscraper'] = '[{\"service_name\": \"Doubleclick\", \"source_non_tracking\": \"<script type=\\"text/javascript\\">document.write(\'<scr\'+\'ipt type=\\"text/javascript\\" src=\\"http://ad.360yield.com/adj?p=2800&w=120&h=600&tz=\'+(new Date().getTimezoneOffset())+\'&click3rd=&optin=n\\"><\\/scr\'+\'ipt>\');</script>\", \"weight\": 1, \"service_kind\": \"ads\", \"source_tracking\": \"<script type=\\"text/javascript\\">var uid = GPTrid();document.write(\'<div id=\\"\'+uid+\'\\"></div>\');var GPTtag = \\"googletag.cmd.push(function(){googletag.defineSlot(\'/4442/P4442.Playboy/articles\', [[120, 600]], \'\\"+uid+\\"\').addService(googletag.pubads())\\";if(typeof GPTrcmd == \'object\'){for (var k in GPTrcmd) {GPTtag += \\".setTargeting(\'\\"+k+\\"\', \'\\"+GPTrcmd[k]+\\"\')\\";}}GPTtag += \\".setTargeting(\'VMspot\', \'\\"+uid.replace(\'VMspot_\',\'\')+\\"\')\\";GPTtag += \\";googletag.enableServices();googletag.display(\'\\"+uid+\\"\');});\\";eval(GPTtag);if(window.enr_initScan) { window.enr_initScan(uid); }</script>\"}]';
  this.positions_weighted['skyscraper'] = true;
  
  this.positions['toc'] = '[]';
  this.positions_weighted['toc'] = false;
}

Tagging.prototype._has_optin = function(category) {
  var categories, i, tagging = this;
  categories = get_categories(this.source_consent_cookie);
  for (i = 0; i < categories.length; i++) {
    if (categories[i] == category) {
      return true;
    }
  }
  return false;

  function get_categories(name) {
    var split = tagging._get_cookie(name).split(":");
    if (split && typeof split[3] != "undefined") {
      return split[3].split(",");
    } else {
      return [];
    }
  }
}

Tagging.prototype._get_cookie = function(name) {
  if (document.cookie && document.cookie != "") {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
      var cookie = trim(cookies[i]);
      if (cookie.substring(0, name.length + 1) == (name + "=")) {
        return decodeURIComponent(cookie.substring(name.length + 1));
      }
    }
  }
  return "";

  function trim(string) {
    return string.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
  }
}

Tagging.prototype._get_tag_source = function(tag) {
  if (this._get_cookie(this.source_consent_cookie)) {
    if (this._has_optin(tag.service_kind)) {
      return tag.source_tracking;
    } else {
      return tag.source_non_tracking;
    }
  } else {
    if (this.source_default_tracking) {
      return tag.source_tracking;
    } else {
      return tag.source_non_tracking;
    }
  }
}

Tagging.prototype.get_json = function(text) {
  return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(text.replace(/"(\\.|[^"\\])*"/g, '')))
         && eval('(' + text + ')');
}

Tagging.prototype.random_tag = function(position) {
  var tags = [];
  var weighted_tags = [];

  for (index in position) {
    tag = position[index];
    tags[index] = this._get_tag_source(tag);

    for (var i = 0; i < tag.weight; i++) {
      weighted_tags.push(index);
    }
  }

  // Pick a random tag from array based on weight
  var random_index = weighted_tags[Math.floor((Math.random() * weighted_tags.length))];
  return tags[random_index];
}

Tagging.prototype.all_tags = function(position) {
  var tags = [], index, tag;
  for (index in position) {
    tag = position[index];
    tags[index] = this._get_tag_source(tag);
  }
  return tags.join("\n");
}

Tagging.prototype.render = function(slug, context) {
    document.write(this.get_source(slug, context));
}

Tagging.prototype.get_source = function(slug, context) {
  if (typeof this.positions[slug] == 'undefined') {
    // This position doesn't exist, call the autodetect
    this._detect(slug);
  } else {
    var position = this.get_json(this.positions[slug]);
    var tag_source = "";

    if (this.positions_weighted[slug]) {
      tag_source = this.random_tag(position)
    } else {
      tag_source = this.all_tags(position);
    }

    // Replace variables
    var variables = {};
    for (variable in this.context) {
      variables[variable] = this.context[variable];
    }
    for (variable in context) {
      variables[variable] = context[variable];
    }
    tag_source = this._replace_variables(tag_source, variables);

    // Remove unset variables and return result
    return tag_source.replace(/\$\w+/g, "").replace(/\${\w+}/g, "");
  }
  return '';
}

Tagging.prototype.log = function(err) {
  //this._load(error_endpoint);
}

Tagging.prototype._load = function(url) {
  var head = document.getElementsByTagName('head')[0] || document.documentElement,
      script = document.createElement('script');

  script.type = 'text/javascript';
  script.src = url;
  head.appendChild(script);
}

Tagging.prototype._detect = function(position) {
  this._load(this.autodetect_url + this.site +'/'+ this.zone +'/' + position + '/');
}

Tagging.prototype._replace_variables = function(content, variables) {
  var RE_VALID_IDENT = /^[a-zA-Z_]\w*$/;
  for (variable in variables) {
    if (RE_VALID_IDENT.test(variable)) {
      var regexes = [new RegExp('\\$' + variable, 'g'), new RegExp('\\${' + variable + '}', 'g')];

      for (re in regexes) {
        content = content.replace(regexes[re], variables[variable]);
      }
    } else {
      throw "'" + variable + "' is not a valid identifier.";
    }
  }
  return content;
}



