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