Added marker to specify, wether min/max-width references page or container
[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   is_pagewidth = {},
35   pagewidth,
36   rendered = {},
37   visible = {},
38   rendering = false,
39   resize_timer,
40   queue = [],
41   output = [];
42
43
44   /*
45    * Configuration-Options for jQuery.openx
46    *
47    * Since the domain-name of the ad-server is the only required parameter,
48    * jQuery.openx for convenience can be configured with only that one
49    * parameter. For example: "jQuery.openx('openx.example.org');". If more
50    * configuration-options are needed, they must be specified as an object.
51    * For example: "jQuery.openx({'server': 'openx.example.org', ... });".
52    *
53    *
54    * Server-Settings:
55    *
56    * server:        string  Name of the server, without protocol or port. For
57    *                        example "openx.example.org". This option is
58    *                        REQUIRED.
59    * protocol:              Optional parameter.
60    *                http:   All connections to the ad-server are made via HTTP.
61    *                https:  All connections to the ad-server are made via HTTPS.
62    *                        If empty, document.location.protocol will be used.
63    * http_port:     number  Port-Number for HTTP-connections to the ad-server
64    *                        (only needed, when it is not the default-value 80).
65    * https_port:            Port-Number for HTTPS-connections to the ad-server
66    *                        (only needed, when it is not the default-value 443).
67    *
68    *
69    * Seldom needed special Server-Settings (these parameters are only needed,
70    * if the default delivery-configration of the OpenX-Server was changed):
71    *
72    * path:          string  Path to delivery-scripts. DEFAULT: "/www/delivery".
73    * fl:            string  Flash-Include-Script. DEFAULT: "fl.js".
74    *
75    *
76    * Delivery-Options (for details and explanations see the see:
77    * http://www.openx.com/docs/2.8/userguide/single%20page%20call):
78    *
79    * block:         1       Don't show the banner again on the same page.
80    *                0       A Banner might be shown multiple times on the same
81    *                        page (DEFAULT).
82    * blockcampaign: 1       Don't show a banner from the same campaign again on
83    *                        the same page.
84    *                0       A Banner from the same campaign might be shown
85    *                        muliple times on the same page (DEFAULT).
86    * target:        string  The value is addes as the HTML TARGET attribute in
87    *                        the ad code. Examples for sensible values: "_blank",
88    *                        "_top".
89    * withtext:      1       Show text below banner. Enter this text in the
90    *                        Banner properties page.
91    *                0       Ignore the text-field from the banner-properties
92                             (DEFAULT).
93    * charset:       string  Charset used, when delivering the banner-codes.
94    *                        If empty, the charset is guessed by OpenX. Examples
95    *                        for sensible values: "UTF-8", "ISO-8859-1".
96    *
97    *
98    * Other settings:
99    *
100    * selector:      string  A selector for selecting the DOM-elements, that
101    *                        should display ad-banners. DEFAULT: ".oa".
102    *                        See: http://api.jquery.com/category/selectors/
103    * min_prefix:    string  Prefix for the encoding of the minmal width as
104    *                        CSS-class. DEFAULT: "min_".
105    * max_prefix:    string  Prefix for the encoding of the maximal width as
106    *                        CSS-class. DEFAULT: "max_".
107    * pw_marker:     string  CSS-class, that marks the encoded maximal and minmal
108    *                        width as page width. DEFAULT: "pw".
109    * resize_delay:  number  Number of milliseconds to wait, before a
110    *                        recalculation of the visible ads is scheduled.
111    *                        If the value is choosen to small, a recalculation
112    *                        might be scheduled, while resizing is still in
113    *                        progress. DEFAULT: 200.
114    * debug:         boolean Turn on/off console-debugging. DEFAULT: false.
115    */
116   $.openx = function( options ) {
117
118     if (domain) {
119       if (console.error) {
120         console.error('jQuery.openx was already initialized!');
121         console.log('Configured options: ', _options);
122       }
123       return;
124     }
125
126     /** Enable convenient-configuration */
127     if (typeof(options) == 'string')
128       options = { 'server': options };
129
130     _options = options;
131
132     if (!options.server) {
133       if (console.error) {
134         console.error('Required option "server" is missing!');
135         console.log('options: ', options);
136       }
137       return;
138     }
139
140     settings = $.extend(
141       {
142         'protocol': document.location.protocol,
143         'delivery': '/www/delivery',
144         'fl': 'fl.js',
145         'selector': '.oa',
146         'min_prefix': 'min_',
147         'max_prefix': 'max_',
148         'pw_marker': 'pw',
149         'resize_delay': 200,
150         'debug': false
151       },
152       options
153       );
154
155     domain = settings.protocol + '//';
156     domain += settings.server;
157     if (settings.protocol === 'http:' && settings.http_port)
158       domain += ':' + settings.http_port;
159     if (settings.protocol === 'https:' && settings.https_port)
160       domain += ':' + settings.https_port;
161
162     if (settings.debug && console.debug)
163       console.debug('Ad-Server: ' + domain);
164
165     /**
166      * Without this option, jQuery appends an timestamp to every URL, that
167      * is fetched via $.getScript(). This can mess up badly written
168      * third-party-ad-scripts, that assume that the called URL's are not
169      * altered.
170      */
171     $.ajaxSetup({ 'cache': true });
172
173     /**
174      * jQuery.openx only works with "named zones", because it does not know,
175      * which zones belong to which website. For mor informations about
176      * "named zones" see:
177      * http://www.openx.com/docs/2.8/userguide/single%20page%20call
178      *
179      * For convenience, jQuery.openx only fetches banners, that are really
180      * included in the actual page. This way, you can configure jQuery.openx
181      * with all zones available for your website - for example in a central
182      * template - and does not have to worry about performance penalties due
183      * to unnecessarily fetched banners.
184      */
185     for(name in OA_zones) {
186       $(settings.selector).each(function() {
187         var
188         id,
189         classes,
190         i,
191         min = new RegExp('^' + settings.min_prefix + '([0-9]+)$'),
192         max = new RegExp('^' + settings.max_prefix + '([0-9]+)$'),
193         match;
194         if (this.id === name) {
195           id = 'oa_' + ++count;
196           slots[id] = this;
197           min_width[id] = 0;
198           max_width[id] = Number.MAX_VALUE;
199           is_pagewidth[id] = false;
200           classes = this.className.split(/\s+/);
201           for (i=0; i<classes.length; i++) {
202             match = min.exec(classes[i]);
203             if (match)
204               min_width[id] = +match[1];
205             match = max.exec(classes[i]);
206             if (match)
207               max_width[id] = +match[1];
208             is_pagewidth[id] = classes[i] === settings.pw_marker;
209           }
210           rendered[id] = false;
211           visible[id] = false;
212           if (settings.debug && console.debug)
213             console.debug(
214                 'Slot ' + count + ': ' + this.id
215                 + (is_pagewidth[id] ? ', pagewidth: ' : ', width: ')
216                 + min_width[id]
217                 + (max_width[id] != Number.MAX_VALUE ? '-' + max_width[id] : '')
218                 );
219         }
220       });
221     }
222
223     /** Add resize-event */
224     $(window).resize(function() {
225       clearTimeout(resize_timer);
226       resize_timer = setTimeout(recalculate_visible , settings.resize_timeout);
227     });
228
229     /** Fetch the JavaScript for Flash and schedule the initial fetch */
230     $.getScript(domain + settings.delivery + '/' + settings.fl, recalculate_visible);
231
232   }
233
234   function recalculate_visible() {
235
236     pagewidth = $(document).width();
237     if (settings.debug && console.debug)
238       console.debug('Scheduling recalculation of visible banners for width ' + pagewidth);
239     if (!rendering)
240       fetch_ads();
241     
242   }
243
244   function fetch_ads() {
245
246     /** Guide rendering-process for early restarts */
247     rendering = true;
248
249     if (settings.debug && console.debug)
250       console.debug('Starting recalculation of visible banners for width ' + pagewidth);
251
252     var name, width, src = domain + settings.delivery + '/spc.php';
253
254     /** Order banners for all zones that were found on the page */
255     src += '?zones=';
256     for(id in slots) {
257       width =
258           is_pagewidth[id]
259           ? pagewidth
260           : Math.round($(slots[id]).parent().width());
261       visible[id] = width >= min_width[id] && width <= max_width[id];
262       if (visible[id]) {
263         if (!rendered[id]) {
264           queue.push(id);
265           src += escape(id + '=' + OA_zones[slots[id].id] + "|");
266           rendered[id] = true;
267           if (settings.debug && console.debug)
268             console.debug('Fetching banner ' + slots[id].id);
269         }
270         else {
271           /** Unhide already fetched visible banners */
272           if (settings.debug && console.debug)
273             console.debug('Unhiding already fetched banner ' + slots[id].id);
274           $(slots[id]).slideDown();
275         }
276       }
277       else {
278         /** Hide unvisible banners */
279         if (settings.debug && console.debug)
280           console.debug('Hiding banner ' + slots[id].id);
281         $(slots[id]).hide();
282       }
283     }
284     src += '&nz=1'; // << We want to fetch named zones!
285
286     /**
287      * These are some additions to the URL of spc.php, that are originally
288      * made in spcjs.php
289      */
290     src += '&r=' + Math.floor(Math.random()*99999999);
291     if (window.location)   src += "&loc=" + escape(window.location);
292     if (document.referrer) src += "&referer=" + escape(document.referrer);
293
294     /** Add the configured options */
295     if (settings.block === 1)
296       src += '&block=1';
297     if (settings.blockcampaign === 1)
298       src += '&blockcampaign=1';
299     if (settings.target)
300       src += '&target=' + settings.target;
301     if (settings.withtext === 1)
302       src += '&withtext=1';
303     if (settings.charset)
304       src += '&charset=' + settings.charset;
305
306     /** Add the source-code - if present */
307     if (typeof OA_source !== 'undefined')
308       src += "&source=" + escape(OA_source);
309
310     /** Signal, that this task is done / in progress */
311     pagewidth = undefined;
312
313     /** Fetch data from OpenX and schedule the render-preparation */
314     $.getScript(src, init_ads);
315
316   }
317
318   function init_ads() {
319
320     var i, id, ads = [];
321     for (i=0; i<queue.length; i++) {
322       id = queue[i];
323       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
324         ads.push(id);
325     }
326     queue = ads;
327
328     document.write = document_write;
329     document.writeln = document_write;
330
331     render_ads();
332
333   }
334
335   function render_ads() {
336
337     while (queue.length > 0) {
338
339       var result, src, inline;
340
341       id = queue.shift();
342       node = $(slots[id]);
343
344       if (settings.debug && console.debug)
345         console.debug('Rendering banner ' + slots[id].id);
346
347       node.slideDown();
348
349       // node.append(id + ": " + node.attr('class'));
350
351       /**
352        * If output was added via document.write(), this output must be
353        * rendered before other banner-code from the OpenX-server is rendered!
354        */
355       insert_output();
356
357       while ((result = /<script/i.exec(OA_output[id])) != null) {
358         node.append(OA_output[id].slice(0,result.index));
359         /** Strip all text before "<script" from OA_output[id] */
360         OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
361         result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
362         if (result == null) {
363           /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
364           // alert(OA_output[id]);
365           OA_output[id] = "";
366         }
367         else {
368           /** Remember iinline-code, if present */
369           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!
370           inline = result[2];
371           /** Strip all text up to and including "</script>" from OA_output[id] */
372           OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
373           result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
374           if (result == null) {
375             /** script-tag with inline-code: execute inline-code! */
376             result = /^\s*<.*$/m.exec(inline);
377             if (result != null) {
378               /** Remove leading HTML-comments, because IE will stumble otherwise */
379               inline = inline.slice(result[0].length,inline.length);
380             }
381             $.globalEval(inline);
382             insert_output(); // << The executed inline-code might have called document.write()!
383           }
384           else {
385             /** script-tag with src-URL! */
386             if (OA_output[id].length > 0)
387               /** The banner-code was not rendered completely yet! */
388               queue.unshift(id);
389             /** Load the script and halt all work until the script is loaded and executed... */
390             $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
391             return;
392           }
393         }
394       }
395
396       node.append(OA_output[id]);
397       OA_output[id] = "";
398     }
399
400     /** All entries from OA_output were rendered */
401
402     id = undefined;
403     node = undefined;
404     rendering = false;
405
406     if (settings.debug && console.debug)
407       console.debug('Recalculation of visible banners done!');
408
409     /** Restart rendering, if new task was queued */
410     if (pagewidth)
411       fetch_ads();
412
413   }
414
415   /** This function is used to overwrite document.write and document.writeln */
416   function document_write() {
417
418     if (id == undefined)
419       return;
420
421     for (var i=0; i<arguments.length; i++)
422       output.push(arguments[i]);
423
424     if (id != queue[0])
425       /**
426        * Re-Add the last banner-code to the working-queue, because included
427        * scripts had added markup via document.write(), which is not
428        * proccessed yet.
429        * Otherwise the added markup would be falsely rendered together with
430        * the markup from the following banner-code.
431        */
432       queue.unshift(id);
433
434   }
435
436   /**
437    * This function prepends the collected output from calls to
438    * document_write() to the current banner-code.
439    */
440   function insert_output() {
441
442     if (output.length > 0) {
443       output.push(OA_output[id]);
444       OA_output[id] = "";
445       for (i=0; i<output.length; i++)
446         OA_output[id] += output[i];
447       output = [];
448     }
449
450   }
451
452 })( jQuery, window, document );
453
454 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!