Tagging = function(context) {
  this.site = 'grazia-nl-grz';
  this.zone = 'home';
  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'] = '[{\"source\": \"<script type=\\"text/javascript\\">if (new Tagging().zone == \'home\') {  document.write(\'<scr\'+\'ipt src=\\"http://t.254a.com/pixel?id=1398586&t=1\\"></scr\'+\'ipt>\');}</script>\", \"weight\": null}, {\"source\": \"<!-- 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 = (\'\'.length > 0) ? \'&c6=\'+escape(\'\') : \'\';cts_stir_segment = (\'${stir_segment_zone}\'.length > 0) ? \'&c6=\'+escape(\'${stir_segment_zone}\') : \'\';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 -->\", \"weight\": null}, {\"source\": \"<script language=\'JavaScript1.1\' type=\'text/javascript\'>(\'sanoma\'.length != 0) ? stir_customer = \'sanoma\' : stir_customer = \'sanoma\'; (\'\'.length != 0) ? stir_counter = \'\' : stir_counter = \'stir\';(\'lifestyle\'.length != 0) ? stir_channel = \'&amp;ns_channel=lifestyle\' : 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 = \'\';(\'sanomadigital-vrouwen\'.length != 0) ? stir_stir4 = \'&amp;ns_stir4=sanomadigital-vrouwen\' : 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+\\"/grazia/s?\\"+stir_counter+stir_channel+stir_webdir+stir_context+stir_auto+stir_stir4);</script>\", \"weight\": null}, {\"source\": \"<script type=\\"text/javascript\\">xtnv = document;xtsd = location.protocol.indexOf(\'https\') >-1 ? \\"https://logc1210\\" : \\"http://logc210\\";xtdmc = \\".grazia.nl\\";xtsite = \\"472561\\";xtn2 = \\"\\";xtpage = \\"${at_xtpage}\\";xtdi = \\"\\";xt_multc = \\"\\";xt_an = \\"\\";xt_ac = \\"\\";if (window.xtparam!=null){window.xtparam+=xt_multc+\\"&ac=\\"+xt_ac+\\"&an=\\"+xt_an;}else{window.xtparam=xt_multc+\\"&ac=\\"+xt_ac+\\"&an=\\"+xt_an;};document.write(\'<scr\'+\'ipt type=\\"text/javascript\\" src=\\"\'+window.location.protocol+\'//cts.snmmd.nl/lib/js/xtcore.js\\"></scr\'+\'ipt>\');</script>\", \"weight\": null}]';
  this.positions_weighted['footer'] = false;
  
  this.positions['head'] = '[{\"source\": \"<script type=\\"text/javascript\\">  var WlWebsiteId=\\"grazia.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>\", \"weight\": null}]';
  this.positions_weighted['head'] = false;
  
  this.positions['medium-rectangle'] = '[{\"source\": \"<div class=\\"adchclearfix\\" style=\\"position:relative;width:auto;\\"><script type=\\"text/javascript\\">  et_size=\'300x250\';  if (\'${dc_keywords}\'.length == 0) kw=wlrcmd; else kw=\'${dc_keywords},\'+wlrcmd;  if (\'${dc_params}\'.length == 0) params=\'\'; else params=\';${dc_params}\';  if (typeof(et_ord)==\'undefined\') et_ord=Math.floor(Math.random()*10000000000000000);   if (typeof(et_dcopt)==\'undefined\'){var et_dcopt=\'dcopt=ist;\'}else{var et_dcopt=\'\'}  if (typeof(et_tile)==\'undefined\') et_tile=1;   if (typeof(et_base)==\'undefined\') et_base=location.protocol.indexOf(\'https\')>-1?\'https://ad.doubleclick.net\':\'http://ad.nl.doubleclick.net\';  et_url=et_base+\'/adj/p4442.grazia.nl/home;sz=\'+et_size+\';\'+et_dcopt+\'tile=\'+(et_tile++)+params+\';smi=\'+et_tile+\';kw=\'+kw+\';ord=\'+et_ord+\'?\'; et_cn=\\"document.getElementById(\'ertdiv\\"+et_tile+\\"\').className=\'adch\'\\"; document.write(\'<a class=\\"adch adch2s\\" id=\\"ertdiv\'+et_tile+\'\\" href=\\"http://www.sanomamedia.nl/nl-web-Cookie_info.php\\" target=\\"_blank\\"></a>\');</script><script type=\\"text/javascript\\">  document.write(\'<scr\'+\'ipt src=\\"\'+et_url+\'\\" type=\\"text/javascript\\"></scr\'+\'ipt>\');if (navigator.userAgent.indexOf(\\"IE\\") != -1) {  document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">document.getElementById(\\"ertdiv\'+et_tile+\'\\").parentNode.className=\\"adchclearfix2\\";</scr\'+\'ipt>\');  document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">document.getElementById(\\"ertdiv\'+et_tile+\'\\").parentNode.parentNode.className+=\\" adchclearfix\\";</scr\'+\'ipt>\');  document.write(\\"<st\\"+\\"yle>.adchclearfix{ display:inline-block;}</st\\"+\\"yle>\\");}</script></div><script type=\\"text/javascript\\">  document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">setTimeout(\\"\'+et_cn+\'\\",2000);</scr\'+\'ipt>\');    document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">et_tp = undefined;</scr\'+\'ipt>\');  </script>\", \"weight\": 1}]';
  this.positions_weighted['medium-rectangle'] = true;
  
  this.positions['multiple-top'] = '[{\"source\": \"<div class=\\"adchclearfix\\" style=\\"position:relative;width:auto;\\"><script type=\\"text/javascript\\">  et_size=\'468x60,728x90\';  if (\'${dc_keywords}\'.length == 0) kw=wlrcmd; else kw=\'${dc_keywords},\'+wlrcmd;  if (\'${dc_params}\'.length == 0) params=\'\'; else params=\';${dc_params}\';  if (typeof(et_ord)==\'undefined\') et_ord=Math.floor(Math.random()*10000000000000000);   if (typeof(et_dcopt)==\'undefined\'){var et_dcopt=\'dcopt=ist;\'}else{var et_dcopt=\'\'}  if (typeof(et_tile)==\'undefined\') et_tile=1;   if (typeof(et_base)==\'undefined\') et_base=location.protocol.indexOf(\'https\')>-1?\'https://ad.doubleclick.net\':\'http://ad.nl.doubleclick.net\';  et_url=et_base+\'/adj/p4442.grazia.nl/home;sz=\'+et_size+\';\'+et_dcopt+\'tile=\'+(et_tile++)+params+\';smi=\'+et_tile+\';kw=\'+kw+\';ord=\'+et_ord+\'?\'; et_cn=\\"document.getElementById(\'ertdiv\\"+et_tile+\\"\').className=\'adch\'\\"; document.write(\'<a class=\\"adch adch2s\\" id=\\"ertdiv\'+et_tile+\'\\" href=\\"http://www.sanomamedia.nl/nl-web-Cookie_info.php\\" target=\\"_blank\\"></a>\');</script><script type=\\"text/javascript\\">  document.write(\'<scr\'+\'ipt src=\\"\'+et_url+\'\\" type=\\"text/javascript\\"></scr\'+\'ipt>\');if (navigator.userAgent.indexOf(\\"IE\\") != -1) {  document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">document.getElementById(\\"ertdiv\'+et_tile+\'\\").parentNode.className=\\"adchclearfix2\\";</scr\'+\'ipt>\');  document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">document.getElementById(\\"ertdiv\'+et_tile+\'\\").parentNode.parentNode.className+=\\" adchclearfix\\";</scr\'+\'ipt>\');  document.write(\\"<st\\"+\\"yle>.adchclearfix{ display:inline-block;}</st\\"+\\"yle>\\");}</script></div><script type=\\"text/javascript\\">  document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">setTimeout(\\"\'+et_cn+\'\\",2000);</scr\'+\'ipt>\');    document.write(\'<scr\'+\'ipt type=\\"text/javascript\\">et_tp = undefined;</scr\'+\'ipt>\');  </script>\", \"weight\": 1}]';
  this.positions_weighted['multiple-top'] = true;
  
  this.positions['pixel'] = '[{\"source\": \"<script type=\\"text/javascript\\">  et_size=\'1x1\';  if (\'${dc_keywords}\'.length == 0) kw=wlrcmd; else kw=\'${dc_keywords},\'+wlrcmd;  if (\'${dc_params}\'.length == 0) params=\'\'; else params=\';${dc_params}\';  if (typeof(et_ord)==\'undefined\') et_ord=Math.floor(Math.random()*10000000000000000);   if (typeof(et_dcopt)==\'undefined\'){var et_dcopt=\'dcopt=ist;\'}else{var et_dcopt=\'\'}  if (typeof(et_tile)==\'undefined\') et_tile=1;   if (typeof(et_base)==\'undefined\') et_base=location.protocol.indexOf(\'https\')>-1?\'https://ad.doubleclick.net\':\'http://ad.nl.doubleclick.net\';  et_url=et_base+\'/adj/p4442.grazia.nl/home;sz=\'+et_size+\';\'+et_dcopt+\'tile=\'+(et_tile++)+params+\';kw=\'+kw+\';ord=\'+et_ord+\'?\';  document.write(\'<scr\'+\'ipt src=\\"\'+et_url+\'\\" type=\\"text/javascript\\"></scr\'+\'ipt>\');</script>\", \"weight\": 1}]';
  this.positions_weighted['pixel'] = true;
  
  this.positions['teaser'] = '[{\"source\": \"<script type=\\"text/javascript\\">  et_size=\'164x115\';  if (\'${dc_keywords}\'.length == 0) kw=wlrcmd; else kw=\'${dc_keywords},\'+wlrcmd;  if (\'${dc_params}\'.length == 0) params=\'\'; else params=\';${dc_params}\';  if (typeof(et_ord)==\'undefined\') et_ord=Math.floor(Math.random()*10000000000000000);   if (typeof(et_dcopt)==\'undefined\'){var et_dcopt=\'dcopt=ist;\'}else{var et_dcopt=\'\'}  if (typeof(et_tile)==\'undefined\') et_tile=1;   if (typeof(et_base)==\'undefined\') et_base=location.protocol.indexOf(\'https\')>-1?\'https://ad.doubleclick.net\':\'http://ad.nl.doubleclick.net\';  et_url=et_base+\'/adj/p4442.grazia.nl/home;sz=\'+et_size+\';\'+et_dcopt+\'tile=\'+(et_tile++)+params+\';kw=\'+kw+\';ord=\'+et_ord+\'?\';  document.write(\'<scr\'+\'ipt src=\\"\'+et_url+\'\\" type=\\"text/javascript\\"></scr\'+\'ipt>\');</script>\", \"weight\": 1}]';
  this.positions_weighted['teaser'] = true;
}

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] = tag.source;

    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 = [];

  for (index in position) {
    tag = position[index];
    tags[index] = tag.source;
  }

  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;
}




