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