Tagging = function(context) {
  this.site = 'sanoma';
  this.zone = 'default';
  this.protocol = window.location.protocol;
  this.autodetect_url = this.protocol + '//cts.p24.hu/service/detect/';
  this.context = context;
  this.positions = {};
  this.positions_weighted = {};

  this.positions['body-start'] = '[{\"service_name\": \"Google Tag Manager\", \"weight\": null, \"source\": \"<noscript><iframe src=\\"//www.googletagmanager.com/ns.html?id=GTM-W8G23V\\"height=\\"0\\" width=\\"0\\" style=\\"display:none;visibility:hidden\\"></iframe></noscript><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':new Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=\'//www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);})(window,document,\'script\',\'dataLayer\',\'GTM-W8G23V\');</script>\"}]';
  this.positions_weighted['body-start'] = false;
  
  this.positions['body-end-adv'] = '[{\"service_name\": \"Adverticum AdServer\", \"weight\": null, \"source\": \"<!-- Goa3: 56609 --><div id=\\"zone56609\\" class=\\"goAdverticum\\"></div>\"}]';
  this.positions_weighted['body-end-adv'] = false;
  
  this.positions['head'] = '[]';
  this.positions_weighted['head'] = false;
  
  this.positions['body-end'] = '[{\"service_name\": \"Adverticum AdServer\", \"weight\": null, \"source\": \"<script type=\\"text/javascript\\" src=\\"//ad.adverticum.net/g3.js\\"></script>\"}]';
  this.positions_weighted['body-end'] = false;
}

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 = [], index, tag;
  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;
}



