2 * (C) Copyright 2012 juplo (http://juplo.de/).
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
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.
19 * See http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
20 * for detailed explanations for the applied best practices.
22 * The semicolon guides our code for poorly written concatenated scripts.
24 ;(function( $, window, document, undefined ) {
28 settings, _options, domain, id, node,
45 * Configuration-Options for jQuery.openx
47 * Since the domain-name of the ad-server is the only required parameter,
48 * jQuery.openx for convenience can be configured with only that one
49 * parameter. For example: "jQuery.openx('openx.example.org');". If more
50 * configuration-options are needed, they must be specified as an object.
51 * For example: "jQuery.openx({'server': 'openx.example.org', ... });".
56 * server: string Name of the server, without protocol or port. For
57 * example "openx.example.org". This option is
59 * protocol: Optional parameter.
60 * http: All connections to the ad-server are made via HTTP.
61 * https: All connections to the ad-server are made via HTTPS.
62 * If empty, document.location.protocol will be used.
63 * http_port: number Port-Number for HTTP-connections to the ad-server
64 * (only needed, when it is not the default-value 80).
65 * https_port: Port-Number for HTTPS-connections to the ad-server
66 * (only needed, when it is not the default-value 443).
69 * Seldom needed special Server-Settings (these parameters are only needed,
70 * if the default delivery-configration of the OpenX-Server was changed):
72 * path: string Path to delivery-scripts. DEFAULT: "/www/delivery".
73 * fl: string Flash-Include-Script. DEFAULT: "fl.js".
76 * Delivery-Options (for details and explanations see the see:
77 * http://www.openx.com/docs/2.8/userguide/single%20page%20call):
79 * block: 1 Don't show the banner again on the same page.
80 * 0 A Banner might be shown multiple times on the same
82 * blockcampaign: 1 Don't show a banner from the same campaign again on
84 * 0 A Banner from the same campaign might be shown
85 * muliple times on the same page (DEFAULT).
86 * target: string The value is addes as the HTML TARGET attribute in
87 * the ad code. Examples for sensible values: "_blank",
89 * withtext: 1 Show text below banner. Enter this text in the
90 * Banner properties page.
91 * 0 Ignore the text-field from the banner-properties
93 * charset: string Charset used, when delivering the banner-codes.
94 * If empty, the charset is guessed by OpenX. Examples
95 * for sensible values: "UTF-8", "ISO-8859-1".
100 * source: array An optional array of JavaScript-Objects, that
101 * define prefixes and suffixes, that should be
102 * added to source-tag defined in OA_source. Each
103 * object can (should) specify the properties "min"
104 * and "max". OA_source will only be altered, when
105 * min <= page-width <= max is true. If this is the
106 * case, the property "prefix" will be prepended to
107 * OA_source and the property "suffix" will be
109 * selector: string A selector for selecting the DOM-elements, that
110 * should display ad-banners. DEFAULT: ".oa".
111 * See: http://api.jquery.com/category/selectors/
112 * min_prefix: string Prefix for the encoding of the minmal width as
113 * CSS-class. DEFAULT: "min_".
114 * max_prefix: string Prefix for the encoding of the maximal width as
115 * CSS-class. DEFAULT: "max_".
116 * pw_marker: string CSS-class, that marks the encoded maximal and minmal
117 * width as page width. DEFAULT: "pw".
118 * resize_delay: number Number of milliseconds to wait, before a
119 * recalculation of the visible ads is scheduled.
120 * If the value is choosen to small, a recalculation
121 * might be scheduled, while resizing is still in
122 * progress. DEFAULT: 500.
123 * debug: boolean Turn on/off console-debugging. DEFAULT: false.
125 $.openx = function( options ) {
129 console.error('jQuery.openx was already initialized!');
130 console.log('Configured options: ', _options);
135 /** Enable convenient-configuration */
136 if (typeof(options) == 'string')
137 options = { 'server': options };
141 if (!options.server) {
143 console.error('Required option "server" is missing!');
144 console.log('options: ', options);
151 'protocol': document.location.protocol,
152 'delivery': '/www/delivery',
155 'min_prefix': 'min_',
156 'max_prefix': 'max_',
164 domain = settings.protocol + '//';
165 domain += settings.server;
166 if (settings.protocol === 'http:' && settings.http_port)
167 domain += ':' + settings.http_port;
168 if (settings.protocol === 'https:' && settings.https_port)
169 domain += ':' + settings.https_port;
171 if (settings.debug && console.debug)
172 console.debug('Ad-Server: ' + domain);
175 * Without this option, jQuery appends an timestamp to every URL, that
176 * is fetched via $.getScript(). This can mess up badly written
177 * third-party-ad-scripts, that assume that the called URL's are not
180 $.ajaxSetup({ 'cache': true });
183 * jQuery.openx only works with "named zones", because it does not know,
184 * which zones belong to which website. For mor informations about
186 * http://www.openx.com/docs/2.8/userguide/single%20page%20call
188 * For convenience, jQuery.openx only fetches banners, that are really
189 * included in the actual page. This way, you can configure jQuery.openx
190 * with all zones available for your website - for example in a central
191 * template - and does not have to worry about performance penalties due
192 * to unnecessarily fetched banners.
194 for(name in OA_zones) {
195 $(settings.selector).each(function() {
200 min = new RegExp('^' + settings.min_prefix + '([0-9]+)$'),
201 max = new RegExp('^' + settings.max_prefix + '([0-9]+)$'),
203 if (this.id === name) {
204 id = 'oa_' + ++count;
207 max_width[id] = Number.MAX_VALUE;
208 is_pagewidth[id] = false;
209 classes = this.className.split(/\s+/);
210 for (i=0; i<classes.length; i++) {
211 match = min.exec(classes[i]);
213 min_width[id] = +match[1];
214 match = max.exec(classes[i]);
216 max_width[id] = +match[1];
217 is_pagewidth[id] = classes[i] === settings.pw_marker;
219 rendered[id] = false;
221 if (settings.debug && console.debug)
223 'Slot ' + count + ': ' + this.id
224 + (is_pagewidth[id] ? ', pagewidth: ' : ', width: ')
226 + (max_width[id] != Number.MAX_VALUE ? '-' + max_width[id] : '')
232 /** Cleanup data for responsive source-tag's */
233 for (i=0; i<settings.source.length; i++) {
234 if (!settings.source[i].min) settings.source[i].min = 0;
235 if (!settings.source[i].max) settings.source[i].max = Number.MAX_VALUE;
236 if (!settings.source[i].prefix) settings.source[i].prefix = '';
237 if (!settings.source[i].suffix) settings.source[i].suffix = '';
240 /** Add resize-event */
241 $(window).resize(function() {
242 clearTimeout(resize_timer);
243 resize_timer = setTimeout(recalculate_visible , settings.resize_timeout);
246 /** Fetch the JavaScript for Flash and schedule the initial fetch */
247 $.getScript(domain + settings.delivery + '/' + settings.fl, recalculate_visible);
251 function recalculate_visible() {
253 pagewidth = $(document).width();
254 if (settings.debug && console.debug)
255 console.debug('Scheduling recalculation of visible banners for width ' + pagewidth);
261 function fetch_ads() {
263 /** Guide rendering-process for early restarts */
266 if (settings.debug && console.debug)
267 console.debug('Starting recalculation of visible banners for width ' + pagewidth);
275 src = domain + settings.delivery + '/spc.php';
277 /** Order banners for all zones that were found on the page */
283 : Math.round($(slots[id]).parent().width());
284 visible[id] = width >= min_width[id] && width <= max_width[id];
288 src += escape(id + '=' + OA_zones[slots[id].id] + "|");
290 if (settings.debug && console.debug)
291 console.debug('Fetching banner ' + slots[id].id);
294 /** Unhide already fetched visible banners */
295 if (settings.debug && console.debug)
296 console.debug('Unhiding already fetched banner ' + slots[id].id);
297 $(slots[id]).slideDown();
301 /** Hide unvisible banners */
302 if (settings.debug && console.debug)
303 console.debug('Hiding banner ' + slots[id].id);
307 src += '&nz=1'; // << We want to fetch named zones!
310 * These are some additions to the URL of spc.php, that are originally
313 src += '&r=' + Math.floor(Math.random()*99999999);
314 if (window.location) src += "&loc=" + escape(window.location);
315 if (document.referrer) src += "&referer=" + escape(document.referrer);
317 /** Add the configured options */
318 if (settings.block === 1)
320 if (settings.blockcampaign === 1)
321 src += '&blockcampaign=1';
323 src += '&target=' + settings.target;
324 if (settings.withtext === 1)
325 src += '&withtext=1';
326 if (settings.charset)
327 src += '&charset=' + settings.charset;
329 /** Calculate responsive source-tag's */
330 for (i=0; i<settings.source.length; i++) {
331 if (pagewidth >= settings.source[i].min
332 && pagewidth <= settings.source[i].max
334 source_prefix = settings.source[i].prefix + source_prefix;
335 source_suffix = source_suffix + settings.source[i].suffix;
339 /** Add the source-code - if present */
340 if (typeof OA_source !== 'undefined'
341 || source_prefix != ''
342 || source_suffix != ''
344 if (settings.debug && console.debug)
345 console.debug('OA_source: ' + source_prefix + OA_source + source_suffix);
346 src += "&source=" + escape(source_prefix + OA_source + source_suffix);
349 /** Signal, that this task is done / in progress */
350 pagewidth = undefined;
352 /** Fetch data from OpenX and schedule the render-preparation */
353 $.getScript(src, init_ads);
357 function init_ads() {
360 for (i=0; i<queue.length; i++) {
362 if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
367 document.write = document_write;
368 document.writeln = document_write;
374 function render_ads() {
376 while (queue.length > 0) {
378 var result, src, inline;
383 if (settings.debug && console.debug)
384 console.debug('Rendering banner ' + slots[id].id);
388 // node.append(id + ": " + node.attr('class'));
391 * If output was added via document.write(), this output must be
392 * rendered before other banner-code from the OpenX-server is rendered!
396 while ((result = /<script/i.exec(OA_output[id])) != null) {
397 node.append(OA_output[id].slice(0,result.index));
398 /** Strip all text before "<script" from OA_output[id] */
399 OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
400 result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
401 if (result == null) {
402 /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
403 // alert(OA_output[id]);
407 /** Remember iinline-code, if present */
408 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!
410 /** Strip all text up to and including "</script>" from OA_output[id] */
411 OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
412 result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
413 if (result == null) {
414 /** script-tag with inline-code: execute inline-code! */
415 result = /^\s*<.*$/m.exec(inline);
416 if (result != null) {
417 /** Remove leading HTML-comments, because IE will stumble otherwise */
418 inline = inline.slice(result[0].length,inline.length);
421 $.globalEval(inline);
425 console.error('Error while executing inline script-code: ' + e.message);
427 insert_output(); // << The executed inline-code might have called document.write()!
430 /** script-tag with src-URL! */
431 if (OA_output[id].length > 0)
432 /** The banner-code was not rendered completely yet! */
434 /** Load the script and halt all work until the script is loaded and executed... */
435 $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
441 node.append(OA_output[id]);
445 /** All entries from OA_output were rendered */
451 if (settings.debug && console.debug)
452 console.debug('Recalculation of visible banners done!');
454 /** Restart rendering, if new task was queued */
460 /** This function is used to overwrite document.write and document.writeln */
461 function document_write() {
466 for (var i=0; i<arguments.length; i++)
467 output.push(arguments[i]);
471 * Re-Add the last banner-code to the working-queue, because included
472 * scripts had added markup via document.write(), which is not
474 * Otherwise the added markup would be falsely rendered together with
475 * the markup from the following banner-code.
482 * This function prepends the collected output from calls to
483 * document_write() to the current banner-code.
485 function insert_output() {
487 if (output.length > 0) {
488 output.push(OA_output[id]);
490 for (i=0; i<output.length; i++)
491 OA_output[id] += output[i];
497 })( jQuery, window, document );
499 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!