Tagging = function(context) {
  this.site = 'laphu';
  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['head'] = '[{\"service_name\": \"Google Adverts\", \"weight\": null, \"source\": \"<script type=\\"text/javascript\\" src=\\"http://ad-blacklist.p24.hu/adx_blacklist.js\\"></script><script type=\\"text/javascript\\">    var noADX = false;    if (        typeof blckAdx != \'undefined\' &&        typeof blckAdx[window.location.hostname] != \'undefined\' &&        blckAdx[window.location.hostname].indexOf(location.pathname) >= 0    ) {        noADX = true;    }</script>\"}]';
  this.positions_weighted['head'] = false;
  
  this.positions['body-start'] = '[{\"service_name\": \"Google Tag Manager\", \"weight\": null, \"source\": \"<noscript><iframe src=\\"//www.googletagmanager.com/ns.html?id=GTM-N5T32D\\"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-N5T32D\');</script>\"}]';
  this.positions_weighted['body-start'] = false;
  
  this.positions['body-end'] = '[{\"service_name\": \"Adverticum AdServer\", \"weight\": null, \"source\": \"<script type=\\"text/javascript\\" src=\\"//ad.adverticum.net/g3.js\\"></script>\"}, {\"service_name\": \"Sanoma/Lap.hu\", \"weight\": null, \"source\": \"<script type=\\"text/javascript\\" src=\\"http://stat.p24.hu/laphu/cts/measuringCode.min.js\\"></script>\"}, {\"service_name\": \"Google Adverts\", \"weight\": null, \"source\": \"<script type=\\"text/javascript\\">    var googleCPLink = (\\"${google_cookie_policy_link}\\" != \\"\\") ? \\"${google_cookie_policy_link}\\" : \\"http://centralmediacsoport.hu/Company/Central-Digitalis-Media-Adatkezelesi-tajekoztato\\";        window.cookieconsent_options = {        \\"message\\"     : \\"A weboldalon cookie-kat haszn&#xE1;lunk, hogy biztons&#xE1;gos b&#xF6;ng&#xE9;sz&#xE9;s mellett a legjobb felhaszn&#xE1;l&#xF3;i &#xE9;lm&#xE9;nyt ny&#xFA;jthassunk.\\",        \\"dismiss\\"       : \\"Rendben!\\",        \\"learnMore\\"   : \\"R&#xE9;szletes le&#xED;r&#xE1;s\\",        \\"link\\"            : googleCPLink,        \\"theme\\"        : \\"//stat.p24.hu/cookiepolicy/styles/custom.css\\",        \\"expiryDays\\" : 1095    };</script><script type=\\"text/javascript\\" src=\\"//stat.p24.hu/cookiepolicy/cookieconsent.min.js\\"></script>\"}]';
  this.positions_weighted['body-end'] = false;
  
  this.positions['body-end-adv'] = '[{\"service_name\": \"Adverticum AdServer\", \"weight\": null, \"source\": \"<!-- Goa3: 2834154 --><div id=\\"zone2834154\\" class=\\"goAdverticum\\"></div>\"}]';
  this.positions_weighted['body-end-adv'] = false;
  
  this.positions['top'] = '[]';
  this.positions_weighted['top'] = false;
  
  this.positions['bottom'] = '[]';
  this.positions_weighted['bottom'] = false;
  
  this.positions['right010'] = '[]';
  this.positions_weighted['right010'] = false;
  
  this.positions['left010'] = '[{\"service_name\": \"Sanoma/Lap.hu\", \"weight\": null, \"source\": \"<script type=\\"text/javascript\\">    var columnItemWidth = 990,        windowWidth = window.innerWidth;        if (990 <= windowWidth && windowWidth <= 1324)    {       columnItemWidth = 655;      }        else if(windowWidth <= 989)    {        columnItemWidth = 320;    }    </script>\"}]';
  this.positions_weighted['left010'] = false;
  
  this.positions['left020'] = '[{\"service_name\": \"Google Adverts\", \"weight\": null, \"source\": \"<div class=\\"ctsGadx\\" style=\\"${google_adx_style}\\"><script type=\\"text/javascript\\">    if (typeof noADX == \'undefined\' || noADX === false) {        document.write(\'<div style=\\"width: \'+columnItemWidth+\'px; text-align: right; font-size: 8px; color: #C6C6C6;\\">HIRDET&#xC9;S</div>\');        var gaAdxSlots = [            {                source : \'(direct)\',                slots: [                    {   slot : \'${google_adx_slot_direct}\'   }                ]            },            {                source : \'hirkereso.hu\',                slots: [                    {   slot : \'${google_adx_slot_hirkereso}\'   }                ]            },            {                source : \'hirstart.hu\',                slots: [                    {   slot : \'${google_adx_slot_hirstart}\'   }                ]            },            {                source : \'kapu.hu\',                slots: [                    {   slot : \'${google_adx_slot_kapu}\'   }                ]            },            {                source : \'startlap\',                slots: [                    {   slot : \'${google_adx_slot_startlap}\'   }                ]            },            {                source: \'adbox\',                slots: [                    {   slot: \'${google_adx_slot_adbox}\'   }                ]            },            {                source: \'hirek.oldal.info\',                slots: [                    {   slot: \'${google_adx_slot_hirekoldalinfo}\'   }                ]            },            {                source: \'newsletter\',                slots: [                    {   slot: \'${google_adx_slot_newsletter}\'   }                ]            },            {                source: \'tombola.hu\',                slots: [                    {   slot: \'${google_adx_slot_tombola}\'   }                ]            },            {                source : \'facebook\',                slots: [                    {   slot : \'${google_adx_slot_facebook_organic}\'   },                    {   slot : \'${google_adx_slot_facebook_cpc}\'   }                ]            },            {                source : \'google\',                slots: [                    {   slot : \'${google_adx_slot_google_organic}\'   },                    {   slot : \'${google_adx_slot_google_cpc}\'   }                ]            }        ];        function readAsCookie(cname) {            var name = cname + \\"=\\";            var ca = document.cookie.split(\';\');            for(var i=0; i<ca.length; i++) {                var c = ca[i].trim();                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);            }            return \\"\\";        }        var utmz = readAsCookie(\'__utmz\');        var utmzVals = (function () {            var pairs = utmz.split(\'.\').slice(4).join(\'.\').split(\'|\');            var ga = {};            for (var i = 0; i < pairs.length; i++) {                var temp = pairs[i].split(\'=\');                ga[temp[0]] = temp[1];            }            return ga;        })();        if (typeof utmzVals.utmccn == \'undefined\') utmzVals.utmccn = \'undefined\';        if (typeof utmzVals.utmcsr == \'undefined\') utmzVals.utmcsr = \'undefined\';        if (typeof utmzVals.utmcmd == \'undefined\') utmzVals.utmcmd = \'undefined\';        var gaAdxSlotIdentifier = \'7774516160\';        for (var x = 0; x < gaAdxSlots.length; x++) {            if (utmzVals.utmccn.indexOf(gaAdxSlots[x].source) != -1 || utmzVals.utmcsr.indexOf(gaAdxSlots[x].source) != -1) {                switch(gaAdxSlots[x].source){                    case \'google\':                    case \'facebook\':                        if (utmzVals.utmcmd == \'cpc\') {                            gaAdxSlotIdentifier = gaAdxSlots[x].slots[1].slot;                        } else if (utmzVals.utmcmd == \'organic\') {                            gaAdxSlotIdentifier = gaAdxSlots[x].slots[0].slot;                        }                        break;                    default:                        gaAdxSlotIdentifier = gaAdxSlots[x].slots[0].slot;                        break;                }                break;            }        }        if (gaAdxSlotIdentifier == \'\') gaAdxSlotIdentifier = \'7774516160\';        gaAdxSlotIdentifier = \'9708075320/\' + gaAdxSlotIdentifier;            google_ad_client = \\"ca-pub-1984646123858990\\";        google_ad_slot = gaAdxSlotIdentifier;        google_ad_width = parseInt(columnItemWidth);        google_ad_height = parseInt(120);        google_max_num_ads = parseInt(3);    } else {        var elements = document.getElementsByClassName(\\"ctsGadx\\");        while(elements.length > 0) {            elements[0].parentNode.removeChild(elements[0]);        }    }</script><script type=\\"text/javascript\\"    src=\\"//pagead2.googlesyndication.com/pagead/show_ads.js\\"></script></div>\"}]';
  this.positions_weighted['left020'] = false;
  
  this.positions['left030'] = '[]';
  this.positions_weighted['left030'] = false;
  
  this.positions['right020'] = '[{\"service_name\": \"Adverticum AdServer\", \"weight\": null, \"source\": \"<!-- Goa3: 3021661 --><div id=\\"zone3021661\\" class=\\"goAdverticum\\"></div>\"}]';
  this.positions_weighted['right020'] = 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;
}



