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 * selector: string A selector for selecting the DOM-elements, that
101 * should display ad-banners. DEFAULT: ".oa".
102 * See: http://api.jquery.com/category/selectors/
103 * min_prefix: string Prefix for the encoding of the minmal width as
104 * CSS-class. DEFAULT: "min_".
105 * max_prefix: string Prefix for the encoding of the maximal width as
106 * CSS-class. DEFAULT: "max_".
107 * pw_marker: string CSS-class, that marks the encoded maximal and minmal
108 * width as page width. DEFAULT: "pw".
109 * resize_delay: number Number of milliseconds to wait, before a
110 * recalculation of the visible ads is scheduled.
111 * If the value is choosen to small, a recalculation
112 * might be scheduled, while resizing is still in
113 * progress. DEFAULT: 200.
114 * debug: boolean Turn on/off console-debugging. DEFAULT: false.
116 $.openx = function( options ) {
120 console.error('jQuery.openx was already initialized!');
121 console.log('Configured options: ', _options);
126 /** Enable convenient-configuration */
127 if (typeof(options) == 'string')
128 options = { 'server': options };
132 if (!options.server) {
134 console.error('Required option "server" is missing!');
135 console.log('options: ', options);
142 'protocol': document.location.protocol,
143 'delivery': '/www/delivery',
146 'min_prefix': 'min_',
147 'max_prefix': 'max_',
155 domain = settings.protocol + '//';
156 domain += settings.server;
157 if (settings.protocol === 'http:' && settings.http_port)
158 domain += ':' + settings.http_port;
159 if (settings.protocol === 'https:' && settings.https_port)
160 domain += ':' + settings.https_port;
162 if (settings.debug && console.debug)
163 console.debug('Ad-Server: ' + domain);
166 * Without this option, jQuery appends an timestamp to every URL, that
167 * is fetched via $.getScript(). This can mess up badly written
168 * third-party-ad-scripts, that assume that the called URL's are not
171 $.ajaxSetup({ 'cache': true });
174 * jQuery.openx only works with "named zones", because it does not know,
175 * which zones belong to which website. For mor informations about
177 * http://www.openx.com/docs/2.8/userguide/single%20page%20call
179 * For convenience, jQuery.openx only fetches banners, that are really
180 * included in the actual page. This way, you can configure jQuery.openx
181 * with all zones available for your website - for example in a central
182 * template - and does not have to worry about performance penalties due
183 * to unnecessarily fetched banners.
185 for(name in OA_zones) {
186 $(settings.selector).each(function() {
191 min = new RegExp('^' + settings.min_prefix + '([0-9]+)$'),
192 max = new RegExp('^' + settings.max_prefix + '([0-9]+)$'),
194 if (this.id === name) {
195 id = 'oa_' + ++count;
198 max_width[id] = Number.MAX_VALUE;
199 is_pagewidth[id] = false;
200 classes = this.className.split(/\s+/);
201 for (i=0; i<classes.length; i++) {
202 match = min.exec(classes[i]);
204 min_width[id] = +match[1];
205 match = max.exec(classes[i]);
207 max_width[id] = +match[1];
208 is_pagewidth[id] = classes[i] === settings.pw_marker;
210 rendered[id] = false;
212 if (settings.debug && console.debug)
214 'Slot ' + count + ': ' + this.id
215 + (is_pagewidth[id] ? ', pagewidth: ' : ', width: ')
217 + (max_width[id] != Number.MAX_VALUE ? '-' + max_width[id] : '')
223 /** Add resize-event */
224 $(window).resize(function() {
225 clearTimeout(resize_timer);
226 resize_timer = setTimeout(recalculate_visible , settings.resize_timeout);
229 /** Fetch the JavaScript for Flash and schedule the initial fetch */
230 $.getScript(domain + settings.delivery + '/' + settings.fl, recalculate_visible);
234 function recalculate_visible() {
236 pagewidth = $(document).width();
237 if (settings.debug && console.debug)
238 console.debug('Scheduling recalculation of visible banners for width ' + pagewidth);
244 function fetch_ads() {
246 /** Guide rendering-process for early restarts */
249 if (settings.debug && console.debug)
250 console.debug('Starting recalculation of visible banners for width ' + pagewidth);
252 var name, width, src = domain + settings.delivery + '/spc.php';
254 /** Order banners for all zones that were found on the page */
260 : Math.round($(slots[id]).parent().width());
261 visible[id] = width >= min_width[id] && width <= max_width[id];
265 src += escape(id + '=' + OA_zones[slots[id].id] + "|");
267 if (settings.debug && console.debug)
268 console.debug('Fetching banner ' + slots[id].id);
271 /** Unhide already fetched visible banners */
272 if (settings.debug && console.debug)
273 console.debug('Unhiding already fetched banner ' + slots[id].id);
274 $(slots[id]).slideDown();
278 /** Hide unvisible banners */
279 if (settings.debug && console.debug)
280 console.debug('Hiding banner ' + slots[id].id);
284 src += '&nz=1'; // << We want to fetch named zones!
287 * These are some additions to the URL of spc.php, that are originally
290 src += '&r=' + Math.floor(Math.random()*99999999);
291 if (window.location) src += "&loc=" + escape(window.location);
292 if (document.referrer) src += "&referer=" + escape(document.referrer);
294 /** Add the configured options */
295 if (settings.block === 1)
297 if (settings.blockcampaign === 1)
298 src += '&blockcampaign=1';
300 src += '&target=' + settings.target;
301 if (settings.withtext === 1)
302 src += '&withtext=1';
303 if (settings.charset)
304 src += '&charset=' + settings.charset;
306 /** Add the source-code - if present */
307 if (typeof OA_source !== 'undefined')
308 src += "&source=" + escape(OA_source);
310 /** Signal, that this task is done / in progress */
311 pagewidth = undefined;
313 /** Fetch data from OpenX and schedule the render-preparation */
314 $.getScript(src, init_ads);
318 function init_ads() {
321 for (i=0; i<queue.length; i++) {
323 if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
328 document.write = document_write;
329 document.writeln = document_write;
335 function render_ads() {
337 while (queue.length > 0) {
339 var result, src, inline;
344 if (settings.debug && console.debug)
345 console.debug('Rendering banner ' + slots[id].id);
349 // node.append(id + ": " + node.attr('class'));
352 * If output was added via document.write(), this output must be
353 * rendered before other banner-code from the OpenX-server is rendered!
357 while ((result = /<script/i.exec(OA_output[id])) != null) {
358 node.append(OA_output[id].slice(0,result.index));
359 /** Strip all text before "<script" from OA_output[id] */
360 OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
361 result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
362 if (result == null) {
363 /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
364 // alert(OA_output[id]);
368 /** Remember iinline-code, if present */
369 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!
371 /** Strip all text up to and including "</script>" from OA_output[id] */
372 OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
373 result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
374 if (result == null) {
375 /** script-tag with inline-code: execute inline-code! */
376 result = /^\s*<.*$/m.exec(inline);
377 if (result != null) {
378 /** Remove leading HTML-comments, because IE will stumble otherwise */
379 inline = inline.slice(result[0].length,inline.length);
381 $.globalEval(inline);
382 insert_output(); // << The executed inline-code might have called document.write()!
385 /** script-tag with src-URL! */
386 if (OA_output[id].length > 0)
387 /** The banner-code was not rendered completely yet! */
389 /** Load the script and halt all work until the script is loaded and executed... */
390 $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
396 node.append(OA_output[id]);
400 /** All entries from OA_output were rendered */
406 if (settings.debug && console.debug)
407 console.debug('Recalculation of visible banners done!');
409 /** Restart rendering, if new task was queued */
415 /** This function is used to overwrite document.write and document.writeln */
416 function document_write() {
421 for (var i=0; i<arguments.length; i++)
422 output.push(arguments[i]);
426 * Re-Add the last banner-code to the working-queue, because included
427 * scripts had added markup via document.write(), which is not
429 * Otherwise the added markup would be falsely rendered together with
430 * the markup from the following banner-code.
437 * This function prepends the collected output from calls to
438 * document_write() to the current banner-code.
440 function insert_output() {
442 if (output.length > 0) {
443 output.push(OA_output[id]);
445 for (i=0; i<output.length; i++)
446 OA_output[id] += output[i];
452 })( jQuery, window, document );
454 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!