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,
44 * Configuration-Options for jQuery.openx
46 * Since the domain-name of the ad-server is the only required parameter,
47 * jQuery.openx for convenience can be configured with only that one
48 * parameter. For example: "jQuery.openx('openx.example.org');". If more
49 * configuration-options are needed, they must be specified as an object.
50 * For example: "jQuery.openx({'server': 'openx.example.org', ... });".
55 * server: string Name of the server, without protocol or port. For
56 * example "openx.example.org". This option is
58 * protocol: Optional parameter.
59 * http: All connections to the ad-server are made via HTTP.
60 * https: All connections to the ad-server are made via HTTPS.
61 * If empty, document.location.protocol will be used.
62 * http_port: number Port-Number for HTTP-connections to the ad-server
63 * (only needed, when it is not the default-value 80).
64 * https_port: Port-Number for HTTPS-connections to the ad-server
65 * (only needed, when it is not the default-value 443).
68 * Seldom needed special Server-Settings (these parameters are only needed,
69 * if the default delivery-configration of the OpenX-Server was changed):
71 * path: string Path to delivery-scripts. DEFAULT: "/www/delivery".
72 * fl: string Flash-Include-Script. DEFAULT: "fl.js".
75 * Delivery-Options (for details and explanations see the see:
76 * http://www.openx.com/docs/2.8/userguide/single%20page%20call):
78 * block: 1 Don't show the banner again on the same page.
79 * 0 A Banner might be shown multiple times on the same
81 * blockcampaign: 1 Don't show a banner from the same campaign again on
83 * 0 A Banner from the same campaign might be shown
84 * muliple times on the same page (DEFAULT).
85 * target: string The value is addes as the HTML TARGET attribute in
86 * the ad code. Examples for sensible values: "_blank",
88 * withtext: 1 Show text below banner. Enter this text in the
89 * Banner properties page.
90 * 0 Ignore the text-field from the banner-properties
92 * charset: string Charset used, when delivering the banner-codes.
93 * If empty, the charset is guessed by OpenX. Examples
94 * for sensible values: "UTF-8", "ISO-8859-1".
99 * selector: string A selector for selecting the DOM-elements, that
100 * should display ad-banners. DEFAULT: ".oa".
101 * See: http://api.jquery.com/category/selectors/
102 * min_prefix: string Prefix for the encoding of the minmal width as
103 * CSS-classname. DEFAULT: "min_".
104 * max_prefix: string Prefix for the encoding of the maximal width as
105 * CSS-classname. DEFAULT: "max_".
106 * resize_delay: number Number of milliseconds to wait, before a
107 * recalculation of the visible ads is scheduled.
108 * If the value is choosen to small, a recalculation
109 * might be scheduled, while resizing is still in
110 * progress. DEFAULT: 200.
111 * debug: boolean Turn on/off console-debugging. DEFAULT: false.
113 $.openx = function( options ) {
117 console.error('jQuery.openx was already initialized!');
118 console.log('Configured options: ', _options);
123 /** Enable convenient-configuration */
124 if (typeof(options) == 'string')
125 options = { 'server': options };
129 if (!options.server) {
131 console.error('Required option "server" is missing!');
132 console.log('options: ', options);
139 'protocol': document.location.protocol,
140 'delivery': '/www/delivery',
143 'min_prefix': 'min_',
144 'max_prefix': 'max_',
151 domain = settings.protocol + '//';
152 domain += settings.server;
153 if (settings.protocol === 'http:' && settings.http_port)
154 domain += ':' + settings.http_port;
155 if (settings.protocol === 'https:' && settings.https_port)
156 domain += ':' + settings.https_port;
158 if (settings.debug && console.debug)
159 console.debug('Ad-Server: ' + domain);
162 * Without this option, jQuery appends an timestamp to every URL, that
163 * is fetched via $.getScript(). This can mess up badly written
164 * third-party-ad-scripts, that assume that the called URL's are not
167 $.ajaxSetup({ 'cache': true });
170 * jQuery.openx only works with "named zones", because it does not know,
171 * which zones belong to which website. For mor informations about
173 * http://www.openx.com/docs/2.8/userguide/single%20page%20call
175 * For convenience, jQuery.openx only fetches banners, that are really
176 * included in the actual page. This way, you can configure jQuery.openx
177 * with all zones available for your website - for example in a central
178 * template - and does not have to worry about performance penalties due
179 * to unnecessarily fetched banners.
181 for(name in OA_zones) {
182 $(settings.selector).each(function() {
187 min = new RegExp('^' + settings.min_prefix + '([0-9]+)$'),
188 max = new RegExp('^' + settings.max_prefix + '([0-9]+)$'),
190 if (this.id === name) {
191 id = 'oa_' + ++count;
194 max_width[id] = Number.MAX_VALUE;
195 classes = this.className.split(/\s+/);
196 for (i=0; i<classes.length; i++) {
197 match = min.exec(classes[i]);
199 min_width[id] = match[1];
200 match = max.exec(classes[i]);
202 max_width[id] = match[1];
204 rendered[id] = false;
206 if (settings.debug && console.debug)
208 'Slot ' + count + ': ' + this.id + ' (' + min_width[id]
209 + (max_width[id] != Number.MAX_VALUE ? '-' + max_width[id] : '')
216 /** Add resize-event */
217 $(window).resize(function() {
218 clearTimeout(resize_timer);
219 resize_timer = setTimeout(recalculate_visible , settings.resize_timeout);
222 /** Fetch the JavaScript for Flash and schedule the initial fetch */
223 $.getScript(domain + settings.delivery + '/' + settings.fl, recalculate_visible);
227 function recalculate_visible() {
229 width = $(document).width();
230 if (settings.debug && console.debug)
231 console.debug('Scheduling recalculation of visible banners for width ' + width);
237 function fetch_ads() {
239 /** Guide rendering-process for early restarts */
242 if (settings.debug && console.debug)
243 console.debug('Starting recalculation of visible banners for width ' + width);
245 var name, src = domain + settings.delivery + '/spc.php';
247 /** Order banners for all zones that were found on the page */
250 visible[id] = width >= min_width[id] && width <= max_width[id];
254 src += escape(id + '=' + OA_zones[slots[id].id] + "|");
256 if (settings.debug && console.debug)
257 console.debug('Fetching banner ' + slots[id].id);
260 /** Unhide already fetched visible banners */
261 if (settings.debug && console.debug)
262 console.debug('Unhiding already fetched banner ' + slots[id].id);
263 $(slots[id]).slideDown();
267 /** Hide unvisible banners */
268 if (settings.debug && console.debug)
269 console.debug('Hiding banner ' + slots[id].id);
273 src += '&nz=1'; // << We want to fetch named zones!
276 * These are some additions to the URL of spc.php, that are originally
279 src += '&r=' + Math.floor(Math.random()*99999999);
280 if (window.location) src += "&loc=" + escape(window.location);
281 if (document.referrer) src += "&referer=" + escape(document.referrer);
283 /** Add the configured options */
284 if (settings.block === 1)
286 if (settings.blockcampaign === 1)
287 src += '&blockcampaign=1';
289 src += '&target=' + settings.target;
290 if (settings.withtext === 1)
291 src += '&withtext=1';
292 if (settings.charset)
293 src += '&charset=' + settings.charset;
295 /** Add the source-code - if present */
296 if (typeof OA_source !== 'undefined')
297 src += "&source=" + escape(OA_source);
299 /** Signal, that this task is done / in progress */
302 /** Fetch data from OpenX and schedule the render-preparation */
303 $.getScript(src, init_ads);
307 function init_ads() {
310 for (i=0; i<queue.length; i++) {
312 if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
317 document.write = document_write;
318 document.writeln = document_write;
324 function render_ads() {
326 while (queue.length > 0) {
328 var result, src, inline;
333 if (settings.debug && console.debug)
334 console.debug('Rendering banner ' + slots[id].id);
338 // node.append(id + ": " + node.attr('class'));
341 * If output was added via document.write(), this output must be
342 * rendered before other banner-code from the OpenX-server is rendered!
346 while ((result = /<script/i.exec(OA_output[id])) != null) {
347 node.append(OA_output[id].slice(0,result.index));
348 /** Strip all text before "<script" from OA_output[id] */
349 OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
350 result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
351 if (result == null) {
352 /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
353 // alert(OA_output[id]);
357 /** Remember iinline-code, if present */
358 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!
360 /** Strip all text up to and including "</script>" from OA_output[id] */
361 OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
362 result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
363 if (result == null) {
364 /** script-tag with inline-code: execute inline-code! */
365 result = /^\s*<.*$/m.exec(inline);
366 if (result != null) {
367 /** Remove leading HTML-comments, because IE will stumble otherwise */
368 inline = inline.slice(result[0].length,inline.length);
370 $.globalEval(inline);
371 insert_output(); // << The executed inline-code might have called document.write()!
374 /** script-tag with src-URL! */
375 if (OA_output[id].length > 0)
376 /** The banner-code was not rendered completely yet! */
378 /** Load the script and halt all work until the script is loaded and executed... */
379 $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
385 node.append(OA_output[id]);
389 /** All entries from OA_output were rendered */
395 if (settings.debug && console.debug)
396 console.debug('Recalculation of visible banners done!');
398 /** Restart rendering, if new task was queued */
404 /** This function is used to overwrite document.write and document.writeln */
405 function document_write() {
410 for (var i=0; i<arguments.length; i++)
411 output.push(arguments[i]);
415 * Re-Add the last banner-code to the working-queue, because included
416 * scripts had added markup via document.write(), which is not
418 * Otherwise the added markup would be falsely rendered together with
419 * the markup from the following banner-code.
426 * This function prepends the collected output from calls to
427 * document_write() to the current banner-code.
429 function insert_output() {
431 if (output.length > 0) {
432 output.push(OA_output[id]);
434 for (i=0; i<output.length; i++)
435 OA_output[id] += output[i];
441 })( jQuery, window, document );
443 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!