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