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