Replaced doubled variable ads with queue
[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   queue = [],
33   output = [];
34
35
36   /*
37    * Configuration-Options for jQuery.openx
38    *
39    * Since the domain-name of the ad-server is the only required parameter,
40    * jQuery.openx for convenience can be configured with only that one
41    * parameter. For example: "jQuery.openx('openx.example.org');". If more
42    * configuration-options are needed, they must be specified as an object.
43    * For example: "jQuery.openx({'server': 'openx.example.org', ... });".
44    *
45    *
46    * Server-Settings:
47    *
48    * server:        string  Name of the server, without protocol or port. For
49    *                        example "openx.example.org". This option is
50    *                        REQUIRED.
51    * protocol:              Optional parameter.
52    *                http:   All connections to the ad-server are made via HTTP.
53    *                https:  All connections to the ad-server are made via HTTPS.
54    *                        If empty, document.location.protocol will be used.
55    * http_port:     number  Port-Number for HTTP-connections to the ad-server
56    *                        (only needed, when it is not the default-value 80).
57    * https_port:            Port-Number for HTTPS-connections to the ad-server
58    *                        (only needed, when it is not the default-value 443).
59    *
60    *
61    * Seldom needed special Server-Settings (these parameters are only needed,
62    * if the default delivery-configration of the OpenX-Server was changed):
63    *
64    * path:          string  Path to delivery-scripts. DEFAULT: "/www/delivery".
65    * fl:            string  Flash-Include-Script. DEFAULT: "fl.js".
66    *
67    *
68    * Delivery-Options (for details and explanations see the see:
69    * http://www.openx.com/docs/2.8/userguide/single%20page%20call):
70    *
71    * block:         1       Don't show the banner again on the same page.
72    *                0       A Banner might be shown multiple times on the same
73    *                        page (DEFAULT).
74    * blockcampaign: 1       Don't show a banner from the same campaign again on
75    *                        the same page.
76    *                0       A Banner from the same campaign might be shown
77    *                        muliple times on the same page (DEFAULT).
78    * target:        string  The value is addes as the HTML TARGET attribute in
79    *                        the ad code. Examples for sensible values: "_blank",
80    *                        "_top".
81    * withtext:      1       Show text below banner. Enter this text in the
82    *                        Banner properties page.
83    *                0       Ignore the text-field from the banner-properties
84                             (DEFAULT).
85    * charset:       string  Charset used, when delivering the banner-codes.
86    *                        If empty, the charset is guessed by OpenX. Examples
87    *                        for sensible values: "UTF-8", "ISO-8859-1".
88    *
89    *
90    * Other settings:
91    *
92    * selector:      string  A selector for selecting the DOM-elements, that
93    *                        should display ad-banners. DEFAULT: ".oa".
94    *                        See: http://api.jquery.com/category/selectors/
95    */
96   $.openx = function( options ) {
97
98     var name, src, errors = [], i;
99
100     if (domain) {
101       if (console.error) {
102         console.error('jQuery.openx was already initialized!');
103         console.log('Configured options: ', _options);
104       }
105       return;
106     }
107
108     /** Enable convenient-configuration */
109     if (typeof(options) == 'string')
110       options = { 'server': options };
111
112     _options = options;
113
114     if (!options.server)
115       errors.push('Required option "server" is missing!');
116     if (errors.length > 0) {
117       if (console.error) {
118         for (i=0; i<errors.length; i++)
119           console.error('Required option "server" is missing!');
120         console.log('options: ', options);
121       }
122       return;
123     }
124
125     settings = $.extend(
126       {
127         'protocol': document.location.protocol,
128         'delivery': '/www/delivery',
129         'fl': 'fl.js',
130         'selector': '.oa',
131         'cache': true
132       },
133       options
134       );
135
136     domain = settings.protocol + '//';
137     domain += settings.server;
138     if (settings.protocol === 'http:' && settings.http_port)
139       domain += ':' + settings.http_port;
140     if (settings.protocol === 'https:' && settings.https_port)
141       domain += ':' + settings.https_port;
142
143     /**
144      * Without this option, jQuery appends an timestamp to every URL, that
145      * is fetched via $.getScript(). This can mess up badly written
146      * third-party-ad-scripts, that assume that the called URL's are not
147      * altered.
148      */
149     $.ajaxSetup({ 'cache': true });
150
151
152     src = domain + settings.delivery + '/spc.php';
153
154     /**
155      * jQuery.openx only works with "named zones", because it does not know,
156      * which zones belong to which website. For mor informations about
157      * "named zones" see:
158      * http://www.openx.com/docs/2.8/userguide/single%20page%20call
159      *
160      * For convenience, jQuery.openx only fetches banners, that are really
161      * included in the actual page. This way, you can configure jQuery.openx
162      * with all zones available for your website - for example in a central
163      * template - and does not have to worry about performance penalties due
164      * to unnecessarily fetched banners.
165      */
166     src += '?zones=';
167     for(name in OA_zones) {
168       $(settings.selector).each(function() {
169         var
170         node = $(this),
171         id;
172         if (node.hasClass(name)) {
173           id = 'oa_' + ++count;
174           slots[id] = node;
175           queue.push(id);
176           src += escape(id + '=' + OA_zones[name] + "|");
177         }
178       });
179     }
180     src += '&nz=1'; // << We want to fetch named zones!
181
182     /**
183      * These are some additions to the URL of spc.php, that are originally
184      * made in spcjs.php
185      */
186     src += '&r=' + Math.floor(Math.random()*99999999);
187     if (window.location)   src += "&loc=" + escape(window.location);
188     if (document.referrer) src += "&referer=" + escape(document.referrer);
189
190     /** Add the configured options */
191     if (settings.block === 1)
192       src += '&block=1';
193     if (settings.blockcampaign === 1)
194       src += '&blockcampaign=1';
195     if (settings.target)
196       src += '&target=' + settings.target;
197     if (settings.withtext === 1)
198       src += '&withtext=1';
199     if (settings.charset)
200       src += '&charset=' + settings.charset;
201
202     /** Add the source-code - if present */
203     if (typeof OA_source !== 'undefined')
204       src += "&source=" + escape(OA_source);
205
206     /** Chain-load the scripts (next script to load is fl.js */
207     $.getScript(src, load_flash);
208
209   }
210
211   function load_flash() {
212
213     $.getScript(domain + settings.delivery + '/' + settings.fl, init_ads);
214
215   }
216
217   function init_ads() {
218
219     var i, id, ads = [];
220     for (i=0; i<queue.length; i++) {
221       id = queue[i];
222       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
223         ads.push(id);
224     }
225     queue = ads;
226
227     document.write = document_write;
228     document.writeln = document_write;
229
230     render_ads();
231
232   }
233
234   function render_ads() {
235
236     while (queue.length > 0) {
237
238       var result, src, inline;
239
240       id = queue.shift();
241       node = slots[id];
242
243       node.slideDown();
244
245       // node.append(id + ": " + node.attr('class'));
246
247       /**
248        * If output was added via document.write(), this output must be
249        * rendered before other banner-code from the OpenX-server is rendered!
250        */
251       insert_output();
252
253       while ((result = /<script/i.exec(OA_output[id])) != null) {
254         node.append(OA_output[id].slice(0,result.index));
255         /** Strip all text before "<script" from OA_output[id] */
256         OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
257         result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
258         if (result == null) {
259           /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
260           // alert(OA_output[id]);
261           OA_output[id] = "";
262         }
263         else {
264           /** Remember iinline-code, if present */
265           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!
266           inline = result[2];
267           /** Strip all text up to and including "</script>" from OA_output[id] */
268           OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
269           result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
270           if (result == null) {
271             /** script-tag with inline-code: execute inline-code! */
272             result = /^\s*<.*$/m.exec(inline);
273             if (result != null) {
274               /** Remove leading HTML-comments, because IE will stumble otherwise */
275               inline = inline.slice(result[0].length,inline.length);
276             }
277             $.globalEval(inline);
278             insert_output(); // << The executed inline-code might have called document.write()!
279           }
280           else {
281             /** script-tag with src-URL! */
282             if (OA_output[id].length > 0)
283               /** The banner-code was not rendered completely yet! */
284               queue.unshift(id);
285             /** Load the script and halt all work until the script is loaded and executed... */
286             $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
287             return;
288           }
289         }
290       }
291
292       node.append(OA_output[id]);
293       OA_output[id] = "";
294     }
295
296     /** All entries from OA_output were rendered */
297
298     id = undefined;
299     node = undefined;
300   }
301
302   /** This function is used to overwrite document.write and document.writeln */
303   function document_write() {
304
305     if (id == undefined)
306       return;
307
308     for (var i=0; i<arguments.length; i++)
309       output.push(arguments[i]);
310
311     if (id != queue[0])
312       /**
313        * Re-Add the last banner-code to the working-queue, because included
314        * scripts had added markup via document.write(), which is not
315        * proccessed yet.
316        * Otherwise the added markup would be falsely rendered together with
317        * the markup from the following banner-code.
318        */
319       queue.unshift(id);
320
321   }
322
323   /**
324    * This function prepends the collected output from calls to
325    * document_write() to the current banner-code.
326    */
327   function insert_output() {
328
329     if (output.length > 0) {
330       output.push(OA_output[id]);
331       OA_output[id] = "";
332       for (i=0; i<output.length; i++)
333         OA_output[id] += output[i];
334       output = [];
335     }
336
337   }
338
339 })( jQuery, window, document );
340
341 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!