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