/**
* Rubicon Project: Solutions Engineering
* Client:          9456/eBay UK
* Name:            rp-ebay-firstlook.js
* Author:          Martin Hill
* Version:         1.0
* Description:     Custom tracking script for smart tag jc, first party data & click tracking
**/

// add indexOf for arrays for browsers that don't have native support, i.e. IE < 9.
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function(item) {
		var i = this.length;
		while (i--) {
			if (this[i] === item) return i;
		}
		return -1;
	}
}

// add array forEach function for browsers that don't have native support, i.e. IE < 9.
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisArg, t[i], i, t);
    }
  };
}

// add array filter function for browsers that don't have native support, i.e. IE < 9.
if (!Array.prototype.filter) {
	Array.prototype.filter = function(fun /*, thisp */) {
		"use strict";
		if (this == null)
			throw new TypeError();

		var t = Object(this);
		var len = t.length >>> 0;
		if (typeof fun != "function")
			throw new TypeError();

		var res = [];
		var thisp = arguments[1];
		for (var i = 0; i < len; i++) {
			if (i in t) {
				var val = t[i]; // in case fun mutates this
				if (fun.call(thisp, val, i, t))
					res.push(val);
			}
		}
		return res;
	};
}

// add array cleaning function
if (!Array.prototype.clean) {
	Array.prototype.clean = function(deleteValue) {
		for (var i = 0; i < this.length; i++) {
			if (this[i] == deleteValue) {         
				this.splice(i, 1);
				i--;
			}
		}
		return this;
	}
}

// add JSON.stringify & parse functions for browsers that don't have native support, i.e. IE < 8.
if (!window.JSON) {
  window.JSON = {
    parse: function (sJSON) { return eval("(" + sJSON + ")"); },
    stringify: function (vContent) {
      if (vContent instanceof Object) {
        var sOutput = "";
        if (vContent.constructor === Array) {
          for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ",", nId++);
          return "[" + sOutput.substr(0, sOutput.length - 1) + "]";
        }
        if (vContent.toString !== Object.prototype.toString) { return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\""; }
        for (var sProp in vContent) { sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringify(vContent[sProp]) + ","; }
        return "{" + sOutput.substr(0, sOutput.length - 1) + "}";
      }
      return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent);
    }
  };
}

// default initialisation object:
var rpx_defaults = {
	clk : false,  // click tracking:    true = enabled, false = disabled, default = false
	rtp : false,  // real time pricing: true = enabled, false = disabled, default = false
	dfp : 'http://ad-emea.doubleclick.net/N3847/adi/ebay.uk.search/keywordsLR;sz=160x600;',  // iframe base url for dfp ad stack
	oif : location.href,
	opg : document.referrer,
	dck : '',
	dbg : false
}

// initialisation object allowed keys
var keys = ['clk','rtp','dfp','oif','opg','dck','dbg'];

// check for initialisation object & sanitise keys
if (typeof rpx_init === 'object') {
	for (var key in rpx_init) {
		if (rpx_init.hasOwnProperty(key)) {
			if (keys.indexOf(key) < 0) {
				delete rpx_init[key];
			}
		}
	}
}

// initialise variables
var rpx_clk = (typeof rpx_init.clk === 'boolean' && rpx_init.clk) ? rpx_init.clk : rpx_defaults.clk;
var rpx_rtp = (typeof rpx_init.rtp === 'boolean' && rpx_init.rtp) ? rpx_init.rtp : rpx_defaults.rtp;
var rpx_dfp = (typeof rpx_init.dfp === 'string' && rpx_init.dfp.indexOf('//ad-emea.doubleclick.net') >= 0 ) ? rpx_init.dfp : rpx_defaults.dfp;
var rpx_src = (typeof rpx_init.oif === 'string' && rpx_init.oif.indexOf('//ad-emea.doubleclick.net') >= 0 ) ? rpx_init.oif : rpx_defaults.oif;
var rpx_url = (typeof rpx_init.opg === 'string' && rpx_init.opg.indexOf('//www.ebay.co.uk') >= 0 ) ? rpx_init.opg : rpx_defaults.opg;
var rpx_pck = (typeof rpx_init.dck === 'string' && rpx_init.dck.indexOf('http://') >= 0 ) ? rpx_init.dck : rpx_defaults.dck;
var rpx_dbg = (typeof rpx_init.dbg === 'boolean' && rpx_init.dbg) ? rpx_init.dbg : rpx_defaults.dbg;

// function to get values for given parameter name (v) from the given url (u)
var rqs = function(u,v)
{
	u = unescape(u);
	u = u.substring(u.indexOf(';')+1);
	v = v.toLowerCase();
	var o = '';
	var p = u.split(';');
	for (i=0;i<p.length;i++){
		var k = p[i].toLowerCase();
		// special case for combining category parameters 'cat' & 'tcat'
		if (v === 'cat') {
			if( k.indexOf(v) >= 0 ) {
    			var pt = p[i].split('=');
				if (pt[0].toLowerCase() === v || pt[0].toLowerCase() === 'tcat') {
					o = o + pt[1] + ',';
				}
			}
		} else {
			if( k.indexOf(v) >= 0 ) {
				var pt = p[i].split('=');
				if (pt[0].toLowerCase() === v) {
					o = o + pt[1] + ',';
				}
			}
		}
	}
	return o.substring(0,o.length-1) || '';
}

// filtering function v = data value, t = filter type
var rpf = function(v,t)
{
	var r;
	var k = ['buy now pay 12 months later','home shopping catalogues','buy now pay later tv','ladies occasion tops','laptops on finance','buy now pay later','bargain shopping','studio catalog','buy Wallpaper','home shopping','nook ereaders','catalogues','catologues','cheap Bras','catalogue','underware','catalogs','catalog','Laptops','buy now pay later$','catalogue request$','kitchen curtains$','ladies nightwear$','occasion dresses$','on line shopping$','online catalogue$','Bourjois Beauty$','clothing womens$','ladies slippers$','mens Levi jeans$','online-shopping$','fashion tights$','home shopping$','catalogue uk$','ladies coats$','red curtains$','catalogue$','cataloge$','catologe$','catalog$','macbook$','laptop$','bras$','$clothes shoppingonline$','$clothes shops online$','$uk catalogue company$','$clothesshops online$','$ladies clarks Shoes$','$ladies clarks Shoes$','$department store$','$catalogueco uk$','$backless bra$','$home shoping$','$shops online$','$catologues$','$mail order$','$catalogue$','$catologes$','$xbox 360$','$catalog$'];
	var c = ['20081','550','2984','3082','87167','267','171228','171243','12576','25298','11874','11890','11724','31388','15200','69323','64353','64354','30090','30078','9800','121902','1293','121904','9801','9834','116503','9835','9837','18306','18174','18179','30164','18180','9843','9844','18206','116504','18183','52636','18185','116505','50541','116507','116506','18186','29748','50175','43114','18187','18211','9855','38708','18230','18238','121975','9859','9860','108779','121976','9861','121977','18262','18263','18270','18275','18276','121978','18277','18283','18290','108780','9858','9873','9872','29751','63732','422','11450','163147','171146','57881','11452','57929','15628','11462','57974','4250','1059','93427','175759','3259','4251','169291','15724','172378','3034','11116','1','137','13881','13905','81','58058','171485','176970','175672','111422','177','171957','111418','179','31530','31491','175673','165','175698','3676','162497','86722','171961','18793','14339','57211','3089','3090','3094','3091','28141','28162','3103','150045','134590','11783','37578','3116','3104','3126','237','11232','617','57','1424','1305','170593','170589','34814','170591','170587','170592','170590','170588','170594','172008','159912','149242','177032','42154','25863','177017','29515','122908','43560','29505','1509','93632','20514','29518','20727','26395','11838','31769','31817','11863','26396','159719','29585','112661','11848','11854','67588','31786','47945','36447','11778','67659','177731','31762','31772','33914','31414','19259','3252','25614','25616','3253','98982','109199','16078','123813','11700','20710','43563','116023','116026','71258','45733','20667','42231','20438','20444','16086','176988','299','20558','109072','20625','63514','3187','631','38219','14308','3197','32254','3199','38208','38204','41986','10033','177073','20697','157967','93838','16080','20571','41968','16092','43502','11827','281','10290','48579','14324','15032','9355','9394','178893','3286','38331','146492','11233','176983','176984','179060','176985','52473','619','1281','20734','20737','20742','20754','63511','1286','63512','870','10542','172206','172187','293','73839','56169','112529','175747','14969','48458','11071','32852','15069','14961','71582','48446','178894','175740','888','21214','16021','21194','30100','16034','36121','30105','21557','7294','177831','158990','177864','3153','15273','1492','20862','33485','1513','79792','4388','40154','36279','123687','21563','64685','98952','11330','16052','16262','36259','21233','16059','21247','22709','74050','13340','64482','260','220','233','11743','131090','169484','14024','169485','82099','75328','36085','9884','61862','33549','33559','38726','33605','61300','61409','14768','174059','99192','61687','23022','33579','33726','174107','174111','14761','14770','177074','169487','30896','3270','14780','174123','177599','122308','1249','139971','139973','54968','40005','52529','40019','48757','41964','45090','31606','31822','31605','45065'];
	if (t === 'kw') {
		r = ''; m = false;
		function f(e,i,a) {
			el = e.toLowerCase();
			kw = decodeURIComponent(v.replace(/[+]/g,' ')).toLowerCase();
			if (kw !== '' && m === false) {
				if  (el.substring(0,1) === '$' && el.substring(el.length-1,el.length) === '$') {  // broad match $<keyword(s)>$
					bm = el.substring(1,el.length-1);
					if (kw.indexOf(bm) >= 0) { r = el; m = true; }
				} else if (el.substring(0,1) !== '$' && el.substring(el.length-1,el.length) === '$') { // wildcard match <keyword(s)>$
					wm = el.substring(0,el.length-1);
					if (kw.indexOf(wm) === 0) { r = el; m = true; }
				} else { // exact match <keyword(s)>
					if (el === kw) { r = el; m = true; }
				}
			}
		}
		k.forEach(f);
	}
	if (t === 'cat') {
		r = '';
		if (v.indexOf(',') >= 0 ) {
			var a,b=[];
			a = v.split(',');
			function al(e,i,a) { // allowed value filtering function
				if (c.indexOf(e) !== -1) { b[i] = e }
			}
			a.forEach(al); // allow only defined values
			function af(e,i,a) { // duplicate filtering function
				if (a.indexOf(e) !== i) { b[i] = undefined }
			}
			b.filter(af); // remove duplicates
			if (b.length > 1) {
				b = b.clean(undefined); // remove undefined values to tidy up array
				r = b.join(',');
			} else if (b.length === 1){
				b = b.clean(undefined); // remove undefined values to tidy up array
				r = b[0];
			} else {
				r = '';
			}
		} else {
			r = (c.indexOf(v) >= 0) ? v : '';
		}
	}
	return r;
}

var rtp = function()
{
	var t = '';
	if (rpx_rtp) {
		try {
			var r = new RubiconInsight();
			t = r.getAsDFPKeyValues(rp_valuation.estimate) + r.getAsDFPKeyValues(rp_valuation.pmp);
		} catch(e) { }
	}
	return t;
}

// process ad response on callback function
rpc = function(rs)
{
	if (rs.status === 'ok') {
		var ad;
		var html;
		for (var i=0; i < rs.ads.length; i++) {
			ad = rs.ads[i];
			if (ad.status === 'ok') {
				if (ad.type === 'script') {
					document.write('<script type=\'text/javascript\'>'+ad.script+'</scr'+'ipt>');
				}
				if (ad.type === 'html') {
					document.write(ad.html);
				}
				// Publisher impression tracking could be added here
				clk();
			} else {
				rpx_params.dfp.u += rtp();
				rpx_params.dfp.u += ';rpg='+encodeURIComponent(rpx_params.data.u);
				document.write('<iframe id=\'rtm_iframe_srplr\' name=\'rtm_iframe_srplr\' title=\'ADVERTISEMENT\' src='+rpx_params.dfp.u+' width=\''+rpx_params.dfp.w+'\' height=\''+rpx_params.dfp.h+'\' marginwidth=\'0\' marginheight=\'0\' hspace=\'0\' vspace=\'0\' frameborder=\'0\' scrolling=\'no\'><\/iframe>');

			}
		}
	}
}

// click tracking functions
var clk = function()
{
	var oif = false;
	var m_out = function() { oif = false; self.blur(); window.focus(); if (rpx_dbg) { console.log('clk.m_out.focus'); }; }
	var m_over = function() { oif = true; if (rpx_dbg) { console.log('clk.m_over.focus'); }; }
	var if_clk = function() {
		if(oif) {
			var adm  = '';
			adm = (typeof rpx_response !== 'undefined');
			if (adm) {
				var a = rpx_response.account;
				var s = rpx_response.site;
				var z = rpx_response.zone;
				var e = rpx_response.size;
				var d = rpx_response.ad;
				var c = rpx_response.creative;
				var u = 'http://optimized-by.rubiconproject.com/t/'+a+'/'+s+'/'+z+'-'+e+'.'+d+'.'+c+'?url=0';
			}
			if (typeof u === 'string') { var ct = new Image(); ct.src = u; console.log(u); }
			if (rpx_pck !== '') { var pc = new Image(); pc.src = rpx_pck; console.log(rpx_pck); }
			if (rpx_dbg) { console.log('clk.if_click') };
		}
	}

	var init = function() {
		var element = document.getElementById('rp-clk-fl');
		element.onmouseover = m_over;
		element.onmouseout = m_out;
	
		if (typeof window.attachEvent !== 'undefined') {
			attachEvent('onblur', if_clk);
			if (rpx_dbg) { console.log('clk.attachEvent.onblur') };
		} else if (typeof window.addEventListener !== 'undefined') {
			addEventListener('blur', if_clk, false);
			if (rpx_dbg) { console.log('clk.addEventListener.onblur') };
		}
	}
	if (rpx_clk) { init(); if (rpx_dbg) { console.log('clk.init') }; }
}

// sessionstorage / cookie set function n = name, v = value, x = expiry (days)
rpsc = function(n,v,x)
{
	if (typeof sessionStorage !== 'undefined') {
		sessionStorage.setItem(n,v);
	} else {
		var xd = new Date();
		xd.setDate(xd.getDate() + x);
		var cv = escape(v) + ((xd === null) ? '' : '; expires=' + xd.toUTCString());
		document.cookie = n + '=' + cv;
	}
}

// parameters object & macros
rpx_params                      = {};
rpx_params.data                 = {};
rpx_params.data.u               = rpx_url;
rpx_params.dfp                  = {};
rpx_params.dfp.u                = rpx_dfp+rpx_src.substring(rpx_src.indexOf(';')+1);
rpx_params.dfp.w                = rqs(rpx_dfp,'sz').substring(0,rqs(rpx_dfp,'sz').indexOf('x'));
rpx_params.dfp.h                = rqs(rpx_dfp,'sz').substring(rqs(rpx_dfp,'sz').indexOf('x')+1,rqs(rpx_dfp,'sz').indexOf('x').length);
//rpx_params.kw                   = rpf(rqs(rpx_src,'kw'),'kw');
rpx_params.visitor              = {};
rpx_params.inventory            = {};
rpx_params.visitor.age          = rqs(rpx_src,'um');
rpx_params.visitor.acorn        = rqs(rpx_src,'ac');
rpx_params.visitor.gender       = rqs(rpx_src,'us');
rpx_params.visitor.viewed       = rpf(rqs(rpx_src,'fvi'),'cat');
rpx_params.visitor.bid          = rpf(rqs(rpx_src,'fbi'),'cat');
rpx_params.visitor.searched     = rpf(rqs(rpx_src,'fse'),'cat');
rpx_params.visitor.bought       = rpf(rqs(rpx_src,'fbo'),'cat');
rpx_params.visitor.interests    = rqs(rpx_src,'seg');
rpx_params.inventory['search']  = rpf(rqs(rpx_src,'kw'),'kw');
rpx_params.inventory.categories = rpf(rqs(rpx_src,'cat'),'cat');

// debugging
console.log(rpx_params);

// set session cookie containing rp_params object
if (rpx_params && typeof rpx_params === 'object') {
	rpsc('rpx_params',JSON.stringify(rpx_params), Date()-1);
}


