Initial version of the script for asynchronous ad-fetching from OpenX
[openx] / openx.js
1 /** Optimized methods for fetching ad-banners via OpenX */
2
3 /** see: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ */
4
5 (function( openx, $, undefined ) {
6
7   var count = 0;
8   var slots = {};
9   var ads = new Array();
10
11
12   openx.fetch_ads = function(server, zones) {
13
14     var spc;
15
16     spc  = "<script type='text/javascript' src='";
17     spc += location.protocol == 'https:' ? 'https://' + server + ':8443':'http://' + server;
18     spc += "/www/delivery/spc.php?zones=";
19
20     /** Only fetch banners, that are really included in this page */
21     $('.oa').each(function() {
22       var node = $(this);
23       for(var name in zones) {
24         if (node.hasClass(name)) {
25           var id = 'oa_' + ++count;
26           slots[id] = node;
27           spc += escape(id + '=' + zones[name] + "|");
28         }
29       }
30     });
31
32     spc += "&amp;nz=1&amp;source=" + escape(OA_source);
33     spc += "&amp;r=" + Math.floor(Math.random()*99999999);
34     spc += "&amp;block=1&amp;charset=UTF-8";
35
36     if (window.location)   spc += "&amp;loc=" + escape(window.location);
37     if (document.referrer) spc += "&amp;referer=" + escape(document.referrer);
38
39     spc+="'></script>";
40
41     document.write(spc);
42     document.write("<script type='text/javascript' src='http://" + server + "/www/delivery/fl.js'></script>");
43   }
44
45
46   openx.render_ads = function() {
47
48     /** Render the fetched ad-banners... */
49     for (var id in slots) {
50       // alert(id + ": " + OA_output[id]);
51       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '') {
52         document.write("<div id='" + id + "'>");
53         document.write(OA_output[id]);
54         document.write("</div>");
55         ads.push(id);
56         // alert('Banner ' + id + ': ' + OA_output[id]);
57       }
58     }
59
60   }
61
62   openx.show_ads = function() {
63
64     /** Show the rendered banners */
65     for (var i=0; i<ads.length; i++) {
66       var ad = $('#'+ads[i]).detach();
67       slots[ads[i]].append(ad);
68     }
69   }
70
71 } ( window.openx = window.openx || {}, jQuery ));