/
Liftium.js
2629 lines (2176 loc) · 74.5 KB
/
Liftium.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Ad Network Optimizer written in Javascript */
/* LiftiumOptions is where the publisher sets up the ad call.
* params:
* pubid - (required) - Liftium Publisher id
* maxHops - the maximum size of the chain (default is 5)
* baseUrl - the prefix url for the config and beacon services (default http://delivery.liftium.com)
* geoUrl - the url to pull the geo targeting data from (default http://geoip.liftium.com/)
* callAd - call this size of an ad once the Liftium code is loaded (without a separate call)
* offline - disable ads
* placement - the placement of the ad, for targeting
* referrer - use this for the referrer instead of document.referrer (used in unit tests)
* exclude_tags - for this page, skip these specific tag ids
* domain - use this for the domain instead of document.domain (used in unit tests)
* config_delay - simulate a slow loading config (used in unit tests)
* error_beacon - turn on/off the error beacon reporting (set to false to turn off)
* google_* - pass these options to the Google AdSense tag. example, google_hints
* kv_* - User defined key values that can be targeted
*/
// If it's not set, define it as an empty object.
var LiftiumOptions = LiftiumOptions || {};
if (! window.Liftium ) { // No need to do this twice
var Liftium = {
baseUrl : LiftiumOptions.baseUrl || "http://delivery.importantmedia.org/",
chain : [],
currents : [],
eventsTracked : 0,
geoUrl : LiftiumOptions.geoUrl || "http://geoip.huddler.com/",
loadDelay : 100,
maxHops : LiftiumOptions.maxHops || 5,
slotHops : [],
rejTags : [],
slotPlacements : [],
slotTimeouts : 0
};
/* ##### Methods are in alphabetical order, call to Liftium.init at the bottom */
/* Simple convenience function for getElementById */
Liftium._ = function(id){
return document.getElementById(id);
};
/* Simple abstraction layer for event handling across browsers */
Liftium.addEventListener = function(item, eventName, callback){
if (window.addEventListener) { // W3C
return item.addEventListener(eventName, callback, false);
} else if (window.attachEvent){ // IE
return item.attachEvent("on" + eventName, callback);
} else {
return false;
}
};
Liftium.beaconCall = function (url, cb){
// Create an image and call the beacon
var img = new Image(0, 0);
// Append a cache buster
if (cb !== false){
url += '&cb=' + Math.random().toString().substring(2,8);
}
if (url.length > 1000){
Liftium.d("Truncating beacon call url to 1000 characters");
url = url.substring(0,1000);
}
img.src = url;
};
/* Set up chain for slot
* a) See if there is a "sampled ad" to try
* b) Check against targeting criteria
* c) Check against frequency/rejection capping criteria
* d) Consider the maximum number of hops, have the last one be a always_fill
*/
Liftium.buildChain = function(slotname) {
Liftium.slotTimer = Liftium.slotTimer || [];
var size = Liftium.getSizeForSlotname(slotname);
// Start the timer;
var now = new Date();
Liftium.slotTimer[slotname] = now.getTime();
var networks = [];
Liftium.chain[slotname] = [];
// Store the placement, clear the source
if (window.LiftiumPlacement) {
Liftium.slotPlacements[slotname] = window.LiftiumPlacement;
window.LiftiumPlacement = null;
} else {
Liftium.slotPlacements[slotname] = LiftiumOptions.placement;
LiftiumOptions.placement = null;
}
// 1x1 is the same thing as 0x0
if (size == "1x1") { size = "0x0"; }
// Do we have this slot?
if (Liftium.e(Liftium.config.sizes[size])){
Liftium.reportError("Unrecognized size in Liftium: " + size, "publisher");
return false;
}
Liftium.setAdjustedValues(Liftium.config.sizes[size]);
// Sort the chain. Done client side for better caching and randomness
Liftium.config.sizes[size].sort(Liftium.chainSort);
// Forced Ad (for troubleshooting)
var forcedAd = Liftium.getRequestVal('liftium_tag');
if (!Liftium.e(forcedAd)){
for (var j = 0, l2 = Liftium.config.sizes[size].length; j < l2; j++){
var tf = Liftium.clone(Liftium.config.sizes[size][j]);
if (tf.tag_id == forcedAd){
Liftium.d("Forcing tagid #" + forcedAd + " on the front of the chain.", 1, tf);
Liftium.config.sizes[size][j].inChain = true;
Liftium.chain[slotname].push(tf);
networks.push(tf.network_name + ", #" + tf.tag_id);
}
}
}
// Build the chain
for (var i = 0, l = Liftium.config.sizes[size].length; i < l; i++){
var t = Liftium.clone(Liftium.config.sizes[size][i]);
// HACK: Don't call DART more than once in the same chain
// TODO: make this a network option
if (t.network_name == "DART" ) {
if ( Liftium.isNetworkInChain(t.network_name, slotname)){
Liftium.d("Ad #" + t.tag_id + " skipped - network already in the chain", 5);
continue;
}
}
if (Liftium.isValidCriteria(t, slotname)){
Liftium.config.sizes[size][i].inChain = true;
Liftium.chain[slotname].push(t);
networks.push(t.network_name + ", #" + t.tag_id);
if (t.always_fill == 1){
Liftium.d("Chain complete - last ad is always_fill", 2, networks);
break;
} else if (Liftium.chain[slotname].length == Liftium.maxHops - 1){
// Chain is full
break;
}
} else {
Liftium.rejTags.push(t.tag_id);
}
}
if (Liftium.chain[slotname].length === 0){
Liftium.reportError("Error building chain for " + slotname + ". No matching tags?");
return false;
}
// AlwaysFill ad.
if (Liftium.chain[slotname][Liftium.chain[slotname].length-1].always_fill != 1){
var gAd = Liftium.getAlwaysFillAd(size, slotname);
if ( gAd !== false) {
Liftium.chain[slotname].push(gAd);
networks.push("AlwaysFill: " + gAd.network_name + ", #" + gAd.tag_id);
}
}
// Sampled ad
var sampledAd = Liftium.getSampledAd(size);
// Business rule: Don't do sampling if a tier 1 ad is present (exclusive)
if (sampledAd !== false && Liftium.isValidCriteria(sampledAd, slotname) && Liftium.chain[slotname][0].tier != "1"){
// HACK: No easy way to put an element on to the beginning of an array in javascript, so reverse/push/reverse
Liftium.chain[slotname].reverse();
Liftium.chain[slotname].push(sampledAd);
Liftium.chain[slotname].reverse();
networks.push("Sampled: " + sampledAd.network_name + ", #" + sampledAd.tag_id);
}
Liftium.d("Chain for " + slotname + " = ", 3, networks);
return true;
};
/* Build up a query string from the supplied array (nvpairs). Optional separator, default ';' */
Liftium.buildQueryString = function(nvpairs, sep){
if (Liftium.e(nvpairs)){
return '';
}
if (typeof sep == "undefined"){
sep = '&';
}
var out = '';
for(var name in nvpairs){
if (Liftium.e(nvpairs[name])){
continue;
}
out += sep + encodeURIComponent(name) + '=' + encodeURIComponent(nvpairs[name]);
}
return out.substring(sep.length);
};
Liftium.callAd = function (sizeOrSlot, iframe) {
if (LiftiumOptions.offline){
Liftium.d("Not printing tag because LiftiumOptions.offline is set");
return false;
}
// FIXME. Seems wrong to do this config check every time an add is called.
// Catch config errors
if (Liftium.e(Liftium.config)){
Liftium.reportError("Error downloading config");
var t = Liftium.fillerAd(sizeOrSlot, "Error downloading config");
document.write(t.tag);
return false;
} else if (Liftium.config.error){
Liftium.reportError("Config error " + Liftium.config.error);
var t2 = Liftium.fillerAd(sizeOrSlot, Liftium.config.error);
document.write(t2.tag);
return false;
}
// Write out a _load div and call the ad
var slotname = Liftium.getUniqueSlotname(sizeOrSlot);
document.write('<div id="' + slotname + '">');
Liftium._callAd(slotname);
document.write("</div>");
return true;
};
/* Do the work of calling the ad tag */
Liftium._callAd = function (slotname, iframe) {
Liftium.d("Calling ad for " + slotname, 1);
var t = Liftium.getNextTag(slotname);
if (t === false) {
t = Liftium.fillerAd(slotname, "getNextTag returned false");
if (iframe) {
Liftium.clearPreviousIframes(slotname);
// TODO write PSA in iframe
} else {
document.write("<!-- Liftium Tag #" + t.tag_id + "-->\n");
document.write(t.tag);
}
return false;
}
// Network Options
Liftium.handleNetworkOptions(t);
Liftium.d("Ad #" + t.tag_id + " for " + t.network_name + " called in " + slotname);
Liftium.d("Config = ", 6, t);
// Redundant for now while I troubleshoot GA
Liftium.trackEvent("tags/" + t.tag_id + "/attempt");
Liftium.trackEvent("tags", "tag", "attempt", t.tag_id);
try { // try/catch block to isolate ad tag errors
if (!Liftium.e(iframe)){
// Clear other load divs for the current slot
Liftium.clearPreviousIframes(slotname);
Liftium.callIframeAd(slotname, t);
} else {
// Capture the current tag for error handling
Liftium.d("Tag :" + t.tag, 5);
Liftium.lastTag = t;
Liftium.lastSlot = slotname;
document.write(t.tag);
Liftium.lastTag = null;
}
} catch (e) {
// This is probably never called, because the document.write hides it...
Liftium.reportError("Error loading tag #" + t.tag_id + ": " + Liftium.print_r(e), "tag");
}
return true;
};
Liftium.callIframeAd = function(slotname, tag, adIframe){
var iframeUrl = Liftium.getIframeUrl(slotname, tag);
if (Liftium.e(iframeUrl) || iframeUrl == "about:blank"){
Liftium.d("Skipping No iframe ad called for No Ad for " + slotname, 3);
return;
}
if (typeof adIframe == "object"){
// Iframe passed in, use it
adIframe.src = iframeUrl;
} else {
// Otherwise, create one and append it to load dive
adIframe = document.createElement("iframe");
var s = tag.size.split("x");
adIframe.src = iframeUrl;
adIframe.width = s[0];
adIframe.height = s[1];
adIframe.scrolling = "no";
adIframe.frameBorder = 0;
adIframe.marginHeight = 0;
adIframe.marginWidth = 0;
adIframe.allowTransparency = true; // For IE
adIframe.id = slotname + '_' + tag.tag_id;
// expandable slots via in-tag magic phrase
// eg. 300x250 with <!-- FORCE 600x250 IFRAME -->
var fs = tag.tag.match(/FORCE [0-9]+x[0-9]+ IFRAME/);
if (fs) {
fs = fs[0].match(/[0-9]+x[0-9]+/);
fs = fs[0].split("x");
Liftium.d("Forced size " + fs[0] + "x" + fs[1] + " for " + slotname, 3);
adIframe.width = fs[0];
adIframe.height = fs[1];
}
Liftium._(slotname).appendChild(adIframe);
}
};
Liftium.callInjectedIframeAd = function (sizeOrSlot, iframeElement){
Liftium.d("Calling injected Iframe Ad for " + sizeOrSlot, 1);
var slotname = Liftium.getContainingDivId(iframeElement);
var t = Liftium.getNextTag(slotname);
var iframeUrl = Liftium.getIframeUrl(slotname, t);
iframeElement.src = iframeUrl;
};
/* Handle Javascript errors with window.onerror */
Liftium.catchError = function (msg, url, line) {
try {
var jsmsg;
if (typeof msg == "object"){
jsmsg = "Error object: " + Liftium.print_r(msg);
} else {
// Careful of the format here, it's processed by error.php
jsmsg = "Error on line #" + line + " of " + url + " : " + msg;
}
Liftium.d("ERROR! " + jsmsg);
if (Liftium.e(Liftium.lastTag)){
Liftium.reportError(jsmsg, "onerror");
} else {
Liftium.reportError("Tag error for tag " + Liftium.print_r(Liftium.lastTag) + "\n" + jsmsg, "tag");
}
// If being called from the unit testing suite, mark it as a failed test
if (! Liftium.e(window.failTestOnError)) { // Set in LiftiumTest
window.LiftiumTest.testFailed();
alert(msg);
}
} catch (e) {
// Oh no. Error in the error handler.
}
return false; // Make sure we let the default error handling continue
};
/* Sort the chain based on the following criteria:
* tier, weighted_random
* The idea behind weighted_random is that we want to sort items
* within the same tier randomly (to take advantage of cream skimming)
* But we also want to favor the higher paying ads
*/
Liftium.chainSort = function(a, b){
var a_tier = parseInt(a.tier, 10) || 0;
var b_tier = parseInt(b.tier, 10) || 0;
if (a_tier < b_tier){
return -1;
} else if (a_tier > b_tier){
return 1;
} else {
// Same tier, sort by weighted random
var a_value= parseFloat(a.adjusted_value) || 0;
var b_value = parseFloat(b.adjusted_value) || 0;
var a_weight = a_value + (a_value * Math.random() * 0.75);
var b_weight = b_value + (b_value * Math.random() * 0.75);
return b_weight - a_weight;
}
};
Liftium.clearPreviousIframes = function(slotname){
var loadDiv = Liftium._(slotname);
if (loadDiv === null){
return false;
}
var iframes = loadDiv.getElementsByTagName("iframe");
for (var i = 0, l = iframes.length; i < l; i++){
iframes[i].style.display = "none";
}
return true;
};
/* By default, javascript passes by value, UNLESS you are passing a javascript
* object, then it passes by reference.
* Yes, I could have extended object prototype, but I hate it when people do that */
Liftium.clone = function (obj){
if (typeof obj == "object" && obj !== null){
var t = new obj.constructor();
for(var key in obj) {
t[key] = Liftium.clone(obj[key]);
}
return t;
} else {
// Some other type (null, undefined, string, number)
return obj;
}
};
/* Handler for messages from XDM */
Liftium.crossDomainMessage = function (message){
XDM.allowedMethods = ["Liftium.iframeHop", "LiftiumTest.testPassed"];
XDM.executeMessage(message.data);
};
/* Set/get cookies. Borrowed from a jquery plugin. Note that options.expires is either a date object,
* or a number of *milli*seconds until the cookie expires */
Liftium.cookie = function(name, value, options) {
if (arguments.length > 1) { // name and value given, set cookie
options = options || {};
if (Liftium.e(value)) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var d;
if (typeof options.expires == 'number') {
d = new Date();
Liftium.d("Setting cookie expire " + options.expires + " milliseconds from " + d.toUTCString(), 5);
d.setTime(d.getTime() + (options.expires));
} else {
d = options.expires;
}
expires = '; expires=' + d.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// CAUTION: Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
Liftium.d("Set-Cookie: " + [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''), 6);
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
return true;
} else { // only name given, get cookie
var cookieValue = null;
if (!Liftium.e(document.cookie)){
var cookies = document.cookie.split(';');
for (var i = 0, l = cookies.length; i < l; i++) {
var cookie = cookies[i].replace( /^\s+|\s+$/g, "");
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
/* Send a message to the debug console if available, otherwise alert */
Liftium.debug = function (msg, level, obj){
if (Liftium.e(Liftium.debugLevel)){
return false;
} else if (level > Liftium.debugLevel){
return false;
}
// Firebug enabled
if (typeof console == "object" && console.dir){
console.log("Liftium: " + msg);
if (arguments.length > 2){
console.dir(obj);
}
// Default console, available on IE 8+, FF 3+ Safari 4+
} else if (typeof console == "object" && console.log){
console.log("Liftium: " + msg);
if (arguments.length > 2){
console.log(Liftium.print_r(obj));
}
}
return true;
};
Liftium.d = Liftium.debug; // Shortcut to reduce size of JS
Liftium.dec2hex = function(d){
var h = parseInt(d, 10).toString(16);
if (h.toString() == "0"){
return "00";
} else {
return h.toUpperCase();
}
};
/* Emulate php's empty(). */
Liftium.empty = function ( v ) {
if (typeof v === 'object') {
for (var key in v) {
return false;
}
return true;
} else {
return v === undefined ||
v === "" ||
v === 0 ||
v === null ||
v === false ||
(typeof v === "number" && isNaN(v)) ||
false; // Everything else
}
};
Liftium.e = Liftium.empty; // Shortcut to make the Javascript smaller
/* Filler ad when we don't have anything better to display. Usually means an error, either with the code
* or the chain
* http://www.peacecorps.gov/index.cfm?shell=resources.media.psa.webbanners
*/
Liftium.fillerAd = function(size, message){
// Pull the height/width out of size
size = size || "300x250"; // TODO/FIXME: figure out size by looking at containing div
var tag = '';
if (!Liftium.e(message)){
tag += '<div class="LiftiumError" style="display:none">Liftium message: ' + message + "</div>";
}
if (size.match(/300x250/)){
tag += '<a href="http://www.peacecorps.gov/psa/webbanners/click?cid=psa15" target="_blank"><img src="http://www.peacecorps.gov/images/webbanners/full/300x250_legacy.gif" width="300" height="250" border="0" alt="Public Service Announcement"/></a>';
} else if (size.match(/728x90/)){
tag += '<a href="http://www.peacecorps.gov/psa/webbanners/click?cid=psa1" target="_blank"><img src="http://www.peacecorps.gov/images/webbanners/full/728x90_thinklocal.gif" width="728" height="90" border="0" alt="Public Service Announcement"/></a>';
} else if (size.match(/160x600/)){
tag += '<a href="http://www.peacecorps.gov/psa/webbanners/click?cid=psa14" target="_blank"><img src="http://www.peacecorps.gov/images/webbanners/full/160x600_legacy.gif" width="160" height="600" border="0" alt="Public Service Announcement"/></a>';
} else {
// No PSA to display for this size.
// Note that this text is specifically referenced in unit tests
tag += '<span style="color:#C0C0C0">No available ads</span>';
}
return {tag_id: 'psa', network_name: "Internal Error PSA", tag: tag, size: size};
};
/* For the supplied type, (text, link, bg), return the color as a hex string.
* Useful for passing to text ad networks to have the ad match the colors of the website
*/
Liftium.getAdColor = function (type){
try {
switch (type){
case "link":
var links = document.getElementsByTagName("a");
if (Liftium.e(links)){
return null;
} else {
return Liftium.normalizeColor(Liftium.getStyle(links[0], "color"));
}
case "bg":
return Liftium.normalizeColor(Liftium.getStyle(document.body, "background-color"));
case "text":
return Liftium.normalizeColor(Liftium.getStyle(document.body, "color"));
default: return null;
}
} catch(e){
// Silence errors from this funciton and just return null.
Liftium.d("Error in Liftium.getAdColor: " + e.message);
return null;
}
};
/* For the supplied element, return the id of the containing div */
Liftium.getContainingDivId = function(element){
// Walk up the dom and find which div it's in
var tempElement = element, tries = 0;
while(tempElement && tries < 10){
if (tempElement.tagName == "DIV" && tempElement.id){
return tempElement.id;
} else {
tempElement = tempElement.parentNode;
}
tries++;
}
return false;
};
Liftium.getPageVar = function(name, defaultVal){
return LiftiumOptions['kv_' + name] || defaultVal || '';
};
/* Get the css style for the supplied element.
TODO: support for float and other idiosyncracies
*/
Liftium.getStyle = function (element, cssprop){
var camelCase = cssprop.replace(/\-(\w)/g, function(all, letter){
return letter.toUpperCase();
});
if (element.currentStyle) { //IE
return element.currentStyle[camelCase] || "";
} else if (document.defaultView && document.defaultView.getComputedStyle) { //Firefox
return document.defaultView.getComputedStyle(element, "")[camelCase] || "";
} else { //try and get inline style
return element.style[camelCase] || "";
}
};
/* Look through the list of ads in the potential chain, and return the best always_fill */
Liftium.getAlwaysFillAd = function(size, slotname){
for (var i = 0, l = Liftium.config.sizes[size].length; i < l; i++){
var t = Liftium.config.sizes[size][i];
if (t.always_fill == 1 && Liftium.isValidCriteria(t, slotname)){
return Liftium.clone(t);
}
}
// Rut roh
return false;
};
/* Get the users country */
Liftium.getCountry = function(){
if (!Liftium.e(Liftium.getCountryFound)){
return Liftium.getCountryFound;
}
var ac, geo = Liftium.geo || window.Geo || { country: "unknown"} ;
if (!Liftium.e(Liftium.getRequestVal('liftium_country'))){
ac = Liftium.getRequestVal('liftium_country');
Liftium.d("Using liftium_country for geo targeting (" + ac + ")", 8);
} else if (Liftium.e(geo.country)) {
// It downloaded, but it's empty, because we were unable to determine the country
Liftium.d("Unable to find a country for this IP, defaulting to US");
return "unknown"; // Bail here so Liftium.getCountryFound doesn't get set
} else {
// Everything worked
ac = geo.country.toLowerCase();
}
if (ac === "gb"){
// Wankers.
ac = "uk";
}
Liftium.getCountryFound = ac;
return ac;
};
/* Normalize the language of the browser.
* FF, Safari, Chrome, Camino use 'language'
* Opera uses browserLanguage and userLanguage
* IE uses 'systemLanguage', and 'userLanguage'
* May vary depending on platform based on what the OS exposes
*/
Liftium.getBrowserLang = function () {
var n = window.navigator;
var l = n.language || n.systemLanguage || n.browserLanguage || n.userLanguage || "";
return l.substring(0,2);
};
/* When an ad does a document.write and we are already passed that point on the page,
* we need to call it in an lframe (document.write can only be executed inline)
* We handle this by calling the iframe from Liftium. This function returns the iframe url */
Liftium.getIframeUrl = function(slotname, tag) {
// Check to see if the tag is already an iframe.
var m = tag.tag.match(/<iframe[\s\S]+src="([^"]+)"/), iframeUrl;
if ( m !== null ){
iframeUrl = m[1].replace(/&/g, "&");
Liftium.d("Found iframe in tag, using " + iframeUrl, 3);
// Handle "No Ad" here so it doesn't get called by iframe
} else if (tag.network_name == "No Ad"){
Liftium.d("Using about:blank for 'No Ad' to avoid iframe", 3);
iframeUrl = "about:blank";
// Special case for DART.
} else if (tag.network_name == "DART"){
iframeUrl = window.LiftiumDART.getUrl(Liftium.slotPlacements[slotname], tag.size, tag.network_options, true);
} else {
var p = { "tag_id": tag.tag_id, "size": tag.size, "slotname": slotname, "placement": Liftium.slotPlacements[slotname]};
iframeUrl = Liftium.baseUrl + "tag/?" + Liftium.buildQueryString(p);
Liftium.d("No iframe found in tag, using " + iframeUrl, 4);
}
return iframeUrl;
};
/* Returns the number of minutes that have elapsed since midnight, according to the users clock */
Liftium.getMinutesSinceMidnight = function(){
var now = new Date();
return (now.getHours() * 60) + now.getMinutes();
};
/* Return the number of minutes since the last reject for the supplied tag id.
* null if there hasn't been a reject
*/
Liftium.getMinutesSinceReject = function(tag_id){
var m = Liftium.getTagStat(tag_id, "m");
if (m === null){
return null;
} else {
return Liftium.getMinutesSinceMidnight() - m;
}
};
/* Iterate through the chain and deliver the next ad tag to be called */
Liftium.getNextTag = function(slotname){
// Do we need to build the chain?
if (Liftium.e(Liftium.chain[slotname])){
if ( Liftium.buildChain(slotname) === false){
Liftium.reportError("Error building chain " + slotname, "chain");
return false;
}
}
// Belt and suspenders to prevent too many hops
Liftium.slotHops[slotname] = Liftium.slotHops[slotname] || 0;
Liftium.slotHops[slotname]++;
if (Liftium.slotHops[slotname] > 10){
Liftium.reportError("Maximum number of hops exceeded: 10", "chain");
return false;
}
// \suspenders
var now = new Date();
var length = Liftium.chain[slotname].length;
var current = Liftium.currents[slotname] || 0;
Liftium.maxHopTime = Liftium.maxHopTime || parseInt(Liftium.config.max_hop_time, 10) || 1500;
if ((now.getTime() - Liftium.slotTimer[slotname]) > Liftium.maxHopTime){
// Maximum fill time has been exceeded, jump to the always_fill
Liftium.d("Liftium.config.max_hop_time=" + Liftium.config.max_hop_time, 5);
Liftium.d("Hop Time of " + Liftium.maxHopTime + " exceeded. Using the always_fill", 2);
Liftium.slotTimeouts++;
// Return the always_fill
var lastOne = length - 1;
Liftium.currents[slotname] = lastOne;
Liftium.chain[slotname][lastOne].started = now.getTime();
Liftium.setTagStat(Liftium.chain[slotname][lastOne].tag_id, "a");
return Liftium.chain[slotname][lastOne];
} else {
for (var i = current, l = length; i < l; i++){
if (!Liftium.e(Liftium.chain[slotname][i].started)){
continue;
} else {
// Win nah!
Liftium.chain[slotname][i].started = now.getTime();
Liftium.currents[slotname] = i;
Liftium.setTagStat(Liftium.chain[slotname][i].tag_id, "a");
return Liftium.chain[slotname][i];
}
}
}
// Rut roh.
Liftium.reportError("No more tags left in the chain - " + slotname + " Last ad in the chain marked as always fill but actually hopped? :" + Liftium.print_r(Liftium.chain[slotname][Liftium.chain[slotname].length-1]), "chain");
// Return a PSA. Note: Do NOT insert the garaunteed fill here.
// If it happens to hop due to a misconfiguration, you'll create a
// never ending loop. Or so I've been told. ;)
// -Nick
return Liftium.fillerAd(slotname, "No more tags left in the chain");
};
Liftium.getPagesSinceSearch = function (){
var kwords = Liftium.getReferringKeywords();
if (Liftium.e(kwords)){
// None, direct traffic
return null;
}
var pagesSince = Liftium.cookie("Lps");
if (Liftium.e(pagesSince)){
pagesSince = 1;
} else {
pagesSince++;
}
Liftium.cookie("Lps", pagesSince);
return null;
};
Liftium.getPropertyCount = function (obj){
try {
if (typeof obj != "object") {
return 0;
}
var c = 0;
for (var property in obj){
if (obj.hasOwnProperty(property)){
c++;
}
}
return c;
} catch (e) {
return 0;
}
};
/* Do what we can to figure out the referring url.
* TODO: Consider if an iframe how to get the url */
Liftium.getReferrer = function () {
return LiftiumOptions.referrer || document.referrer;
};
/* Look at the referring keywords for this page
* TODO: Found this snippet inside ga.js
* l("daum:q,eniro:search_word,naver:query,images.google:q,google:q,yahoo:p,msn:q,bing:q,aol:query,aol:encquery,lycos:query,ask:q,altavista:q,netscape:query,cnn:query,about:terms,mamma:query,alltheweb:q,voila:rdata,virgilio:qs,live:q,baidu:wd,alice:qs,yandex:text,najdi:q,aol:q,mama:query,seznam:q,search:q,wp:szukaj,onet:qt,szukacz:q,yam:k,pchome:q,kvasir:q,sesam:q,ozu:q,terra:query,mynet:q,ekolay:q,rambler:words");
* */
Liftium.getReferringKeywords = function (){
var l = Liftium.getReferrer(), kwords;
var qstring = l.match(/\?(.*)$/);
if (Liftium.e(qstring)){
qstring = [];
} else {
qstring = qstring[1];
}
var varNames = [ "q", "p", "query" ];
for (var i = 0; i < varNames.length; i++){
kwords = Liftium.getRequestVal(varNames[i], '', qstring);
if (!Liftium.e(kwords)) {
break;
}
}
var kwordsCookie = Liftium.cookie("Lrk");
if (!Liftium.e(kwords)){
Liftium.cookie("Lrk", kwords);
return kwords;
} else if (!Liftium.e(kwordsCookie)){
return kwordsCookie;
} else {
return null;
}
};
Liftium.getRequestVal = function(varName, defaultVal, qstring){
var nvpairs = Liftium.parseQueryString(qstring || document.location.search);
if (typeof nvpairs[varName] != "undefined"){
return nvpairs[varName];
} else if (typeof defaultVal != "undefined" ) {
return defaultVal;
} else {
return '';
}
};
/* Look through the list of ads in the potential chain, and find one that is sample-able */
Liftium.getSampledAd = function(size){
// Build up an array of the sample stats.
var sArray = [], total = 0, myRandom = Math.random() * 100;
for (var i = 0, l = Liftium.config.sizes[size].length; i < l; i++){
var sample_rate = parseFloat(Liftium.config.sizes[size][i].sample_rate);
if (Liftium.e(sample_rate)){
continue;
}
total += sample_rate;
Liftium.d("Sample Rate for " + Liftium.config.sizes[size][i].tag_id + " is " + sample_rate, 7);
sArray.push( { "upper_bound": total, "index": i });
}
Liftium.d("Sample Array = ", 7, sArray);
// Now check to see if the random number is in sArray
for (var j = 0, l2 = sArray.length; j < l2; j++){
if (myRandom < sArray[j].upper_bound){
var f = sArray[j].index;
return Liftium.clone(Liftium.config.sizes[size][f]);
}
}
return false;
};
Liftium.getSlotnameFromElement = function(element){
if (typeof element != "object") {
return false;
}
// Walk up the dom and find which slot div it's in
var tempElement = element, tries = 0;
while(tempElement && tries < 10){
if (tempElement.id && tempElement.id.match(/^Liftium_/)){
return tempElement.id;
} else {
tempElement = tempElement.parentNode;
}
tries++;
}
return false;
};
/* Format is $day_{$tag_id}l{$loads}r{$rejects}m{$lastrejecttime}
* r and m are optional, only if there is a reject
* $day -- 0 to 6, where 0 is Sunday
* $tag_id -- you better know what this is
* $loads -- number of loads today
* $rejects -- number of rejects today
* $lastrejecttime -- minutes since midnight of the last reject
*/
Liftium.getStatRegExp = function(tag_id){
return new RegExp(Liftium.now.getDay() + '_' + tag_id + 'l([0-9]+)a([0-9]+)r*([0-9]*)m*([0-9]*)' );
};
/* Figure out what size a slot is by looking at the config.
* Should we pass a map of sizes->slotnames in the config? Maybe, but it would make it bigger...
*/
Liftium.getSizeForSlotname = function (slotname){
var match = slotname.match(/[0-9]{1,3}x[0-9]{1,3}/);
if (match !== null){
return match[0];
}
for (var slot in Liftium.config.slotnames){
if (typeof Liftium.config.slotnames[slot] == "function"){
// Prototype js library overwrites the array handler and adds crap. EVIL.
continue;
}
if (slot == slotname){
return Liftium.config.slotnames[slot];
}
}
return false;
};
/* Get loads/rejects for a tag. Type = "l" for loads, "r" for rejects,
* and "m" for the minutes since midnight of the last rejection */
Liftium.getTagStat = function (tag_id, type){
var stat = null;
if (Liftium.e(Liftium.tagStats)){
Liftium.tagStats = Liftium.getRequestVal("liftium_tag_stats", null) || Liftium.Storage.getEngine().set("LTS3") || "";
}
var statMatch = Liftium.tagStats.match(Liftium.getStatRegExp(tag_id));
if (!Liftium.e(statMatch)){
var len = statMatch.length;
if (type === "l" && len >= 3){
stat = statMatch[1];
} else if (type === "a" && len >= 4){
stat = statMatch[2];
} else if (type === "r" && len >= 5){
stat = statMatch[3];
} else if (type === "m" && len >= 6){
stat = statMatch[4];
}