Fetch on resize: "rendered" keeps track of already fetched banners
[openx] / jquery.openx.js
1 /*
2  * (C) Copyright 2012 juplo (http://juplo.de/).
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the GNU Lesser General Public License
6  * (LGPL) version 3.0 which accompanies this distribution, and is available at
7  * http://www.gnu.org/licenses/lgpl-3.0.html
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * Contributors:
15  * - Kai Moritz
16  */
17
18 /*
19  * See http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
20  * for detailed explanations for the applied best practices.
21  *
22  * The semicolon guides our code for poorly written concatenated scripts.
23  */
24 ;(function( $, window, document, undefined ) {
25
26   var
27
28   settings, _options, domain, id, node,
29
30   count = 0,
31   slots = {},
32   min_width = {},
33   max_width = {},
34   width,
35   rendered = {},
36   queue = [],
37   output = [];
38
39
40   /*
41    * Configuration-Options for jQuery.openx
42    *
43    * Since the domain-name of the ad-server is the only required parameter,
44    * jQuery.openx for convenience can be configured with only that one
45    * parameter. For example: "jQuery.openx('openx.example.org');". If more
46    * configuration-options are needed, they must be specified as an object.
47    * For example: "jQuery.openx({'server': 'openx.example.org', ... });".
48    *
49    *
50    * Server-Settings:
51    *
52    * server:        string  Name of the server, without protocol or port. For
53    *                        example "openx.example.org". This option is
54    *                        REQUIRED.
55    * protocol:              Optional parameter.
56    *                http:   All connections to the ad-server are made via HTTP.
57    *                https:  All connections to the ad-server are made via HTTPS.
58    *                        If empty, document.location.protocol will be used.
59    * http_port:     number  Port-Number for HTTP-connections to the ad-server
60    *                        (only needed, when it is not the default-value 80).
61    * https_port:            Port-Number for HTTPS-connections to the ad-server
62    *                        (only needed, when it is not the default-value 443).
63    *
64    *
65    * Seldom needed special Server-Settings (these parameters are only needed,
66    * if the default delivery-configration of the OpenX-Server was changed):
67    *
68    * path:          string  Path to delivery-scripts. DEFAULT: "/www/delivery".
69    * fl:            string  Flash-Include-Script. DEFAULT: "fl.js".
70    *
71    *
72    * Delivery-Options (for details and explanations see the see:
73    * http://www.openx.com/docs/2.8/userguide/single%20page%20call):
74    *
75    * block:         1       Don't show the banner again on the same page.
76    *                0       A Banner might be shown multiple times on the same
77    *                        page (DEFAULT).
78    * blockcampaign: 1       Don't show a banner from the same campaign again on
79    *                        the same page.
80    *                0       A Banner from the same campaign might be shown
81    *                        muliple times on the same page (DEFAULT).
82    * target:        string  The value is addes as the HTML TARGET attribute in
83    *                        the ad code. Examples for sensible values: "_blank",
84    *                        "_top".
85    * withtext:      1       Show text below banner. Enter this text in the
86    *                        Banner properties page.
87    *                0       Ignore the text-field from the banner-properties
88                             (DEFAULT).
89    * charset:       string  Charset used, when delivering the banner-codes.
90    *                        If empty, the charset is guessed by OpenX. Examples
91    *                        for sensible values: "UTF-8", "ISO-8859-1".
92    *
93    *
94    * Other settings:
95    *
96    * selector:      string  A selector for selecting the DOM-elements, that
97    *                        should display ad-banners. DEFAULT: ".oa".
98    *                        See: http://api.jquery.com/category/selectors/
99    * min_prefix:    string  Prefix for the encoding of the minmal width as
100    *                        CSS-classname. DEFAULT: "min_".
101    * max_prefix:    string  Prefix for the encoding of the maximal width as
102    *                        CSS-classname. DEFAULT: "max_".
103    */
104   $.openx = function( options ) {
105
106     if (domain) {
107       if (console.error) {
108         console.error('jQuery.openx was already initialized!');
109         console.log('Configured options: ', _options);
110       }
111       return;
112     }
113
114     /** Enable convenient-configuration */
115     if (typeof(options) == 'string')
116       options = { 'server': options };
117
118     _options = options;
119
120     if (!options.server) {
121       if (console.error) {
122         console.error('Required option "server" is missing!');
123         console.log('options: ', options);
124       }
125       return;
126     }
127
128     settings = $.extend(
129       {
130         'protocol': document.location.protocol,
131         'delivery': '/www/delivery',
132         'fl': 'fl.js',
133         'selector': '.oa',
134         'min_prefix': 'min_',
135         'max_prefix': 'max_',
136         'cache': true
137       },
138       options
139       );
140
141     domain = settings.protocol + '//';
142     domain += settings.server;
143     if (settings.protocol === 'http:' && settings.http_port)
144       domain += ':' + settings.http_port;
145     if (settings.protocol === 'https:' && settings.https_port)
146       domain += ':' + settings.https_port;
147
148     /**
149      * Without this option, jQuery appends an timestamp to every URL, that
150      * is fetched via $.getScript(). This can mess up badly written
151      * third-party-ad-scripts, that assume that the called URL's are not
152      * altered.
153      */
154     $.ajaxSetup({ 'cache': true });
155
156     /**
157      * jQuery.openx only works with "named zones", because it does not know,
158      * which zones belong to which website. For mor informations about
159      * "named zones" see:
160      * http://www.openx.com/docs/2.8/userguide/single%20page%20call
161      *
162      * For convenience, jQuery.openx only fetches banners, that are really
163      * included in the actual page. This way, you can configure jQuery.openx
164      * with all zones available for your website - for example in a central
165      * template - and does not have to worry about performance penalties due
166      * to unnecessarily fetched banners.
167      */
168     for(name in OA_zones) {
169       $(settings.selector).each(function() {
170         var
171         id,
172         classes,
173         i,
174         min = new RegExp('^' + settings.min_prefix + '([0-9]+)$'),
175         max = new RegExp('^' + settings.max_prefix + '([0-9]+)$'),
176         match;
177         if (this.id === name) {
178           id = 'oa_' + ++count;
179           slots[id] = this;
180           min_width[id] = 0;
181           max_width[id] = Number.MAX_VALUE;
182           classes = this.className.split(/\s+/);
183           for (i=0; i<classes.length; i++) {
184             match = min.exec(classes[i]);
185             if (match)
186               min_width[id] = match[1];
187             match = max.exec(classes[i]);
188             if (match)
189               max_width[id] = match[1];
190           }
191           rendered[id] = false;
192         }
193       });
194     }
195
196     /** Set initial window-width */
197     width = $(document).width();
198
199     /** Fetch the JavaScript for Flash and schedule the initial fetch */
200     $.getScript(domain + settings.delivery + '/' + settings.fl, fetch_ads);
201
202   }
203
204   function fetch_ads() {
205
206     var name, src = domain + settings.delivery + '/spc.php';
207
208     /** Order banners for all zones that were found on the page */
209     src += '?zones=';
210     for(id in slots) {
211       if (width >= min_width[id] && width <= max_width[id]) {
212         queue.push(id);
213         src += escape(id + '=' + OA_zones[slots[id].id] + "|");
214         rendered[id] = true;
215       }
216     }
217     src += '&nz=1'; // << We want to fetch named zones!
218
219     /**
220      * These are some additions to the URL of spc.php, that are originally
221      * made in spcjs.php
222      */
223     src += '&r=' + Math.floor(Math.random()*99999999);
224     if (window.location)   src += "&loc=" + escape(window.location);
225     if (document.referrer) src += "&referer=" + escape(document.referrer);
226
227     /** Add the configured options */
228     if (settings.block === 1)
229       src += '&block=1';
230     if (settings.blockcampaign === 1)
231       src += '&blockcampaign=1';
232     if (settings.target)
233       src += '&target=' + settings.target;
234     if (settings.withtext === 1)
235       src += '&withtext=1';
236     if (settings.charset)
237       src += '&charset=' + settings.charset;
238
239     /** Add the source-code - if present */
240     if (typeof OA_source !== 'undefined')
241       src += "&source=" + escape(OA_source);
242
243     /** Fetch data from OpenX and schedule the render-preparation */
244     $.getScript(src, init_ads);
245
246   }
247
248   function init_ads() {
249
250     var i, id, ads = [];
251     for (i=0; i<queue.length; i++) {
252       id = queue[i];
253       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
254         ads.push(id);
255     }
256     queue = ads;
257
258     document.write = document_write;
259     document.writeln = document_write;
260
261     render_ads();
262
263   }
264
265   function render_ads() {
266
267     while (queue.length > 0) {
268
269       var result, src, inline;
270
271       id = queue.shift();
272       node = $(slots[id]);
273
274       node.slideDown();
275
276       // node.append(id + ": " + node.attr('class'));
277
278       /**
279        * If output was added via document.write(), this output must be
280        * rendered before other banner-code from the OpenX-server is rendered!
281        */
282       insert_output();
283
284       while ((result = /<script/i.exec(OA_output[id])) != null) {
285         node.append(OA_output[id].slice(0,result.index));
286         /** Strip all text before "<script" from OA_output[id] */
287         OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
288         result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
289         if (result == null) {
290           /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
291           // alert(OA_output[id]);
292           OA_output[id] = "";
293         }
294         else {
295           /** Remember iinline-code, if present */
296           src = result[1] + ' ' // << simplifies the following regular expression: the string ends with a space in any case, so that the src-URL cannot be followed by the end of the string emediately!
297           inline = result[2];
298           /** Strip all text up to and including "</script>" from OA_output[id] */
299           OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
300           result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
301           if (result == null) {
302             /** script-tag with inline-code: execute inline-code! */
303             result = /^\s*<.*$/m.exec(inline);
304             if (result != null) {
305               /** Remove leading HTML-comments, because IE will stumble otherwise */
306               inline = inline.slice(result[0].length,inline.length);
307             }
308             $.globalEval(inline);
309             insert_output(); // << The executed inline-code might have called document.write()!
310           }
311           else {
312             /** script-tag with src-URL! */
313             if (OA_output[id].length > 0)
314               /** The banner-code was not rendered completely yet! */
315               queue.unshift(id);
316             /** Load the script and halt all work until the script is loaded and executed... */
317             $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
318             return;
319           }
320         }
321       }
322
323       node.append(OA_output[id]);
324       OA_output[id] = "";
325     }
326
327     /** All entries from OA_output were rendered */
328
329     id = undefined;
330     node = undefined;
331   }
332
333   /** This function is used to overwrite document.write and document.writeln */
334   function document_write() {
335
336     if (id == undefined)
337       return;
338
339     for (var i=0; i<arguments.length; i++)
340       output.push(arguments[i]);
341
342     if (id != queue[0])
343       /**
344        * Re-Add the last banner-code to the working-queue, because included
345        * scripts had added markup via document.write(), which is not
346        * proccessed yet.
347        * Otherwise the added markup would be falsely rendered together with
348        * the markup from the following banner-code.
349        */
350       queue.unshift(id);
351
352   }
353
354   /**
355    * This function prepends the collected output from calls to
356    * document_write() to the current banner-code.
357    */
358   function insert_output() {
359
360     if (output.length > 0) {
361       output.push(OA_output[id]);
362       OA_output[id] = "";
363       for (i=0; i<output.length; i++)
364         OA_output[id] += output[i];
365       output = [];
366     }
367
368   }
369
370 })( jQuery, window, document );
371
372 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!